Remember our last lecture http xkcd com327 PHP
Remember our last lecture? http: //xkcd. com/327/
PHP and Object Orientation Encapsulation, Inheritance, Polymorphism
Creating a Class • Data members • Methods
Object Orientation PHP is an Object-Oriented programming language Fundamental feature of OO is the class PHP classes support Encapsulation Inheritance Polymorphism
What is a Class
What is a Class? Classes Sophisticated ‘variable types’ Data variables (data members) and functions data members (methods) are wrapped up in a class. Collectively, methods data members and methods are referred to as class members An instance of a class is known as an object. of a class object //defining a new class named Robot class Robot { //place class members here. . . }
Instantiating a Class
Instantiating a class using new Once a class has been created, any number of any number object instances of that class can be created. $dog. Robot = new Robot(); Robot() To invoke methods: object->method() -> e. g. <? php. . $dog. Robot = new Robot(); Robot() $dog. Robot ->crawl. Web(); $dog. Robot -> play(); echo $dog. Robot ->talk(); . . . ? >
Defining classes <? php class Person { private $str. Firstname = “Napoleon"; private $str. Surname = “Reyes"; Data members function get. Firstname() { return $this->str. Firstname; } Methods function get. Surname() { return $this->str. Surname; } } // outside the class definition $obj = new Person; // an object of type Person echo "<p>Firstname: ". $obj->get. Firstname(). "</p>"; echo "<p>Surname: ". $obj->get. Surname(). "</p>"; ? > Example 16 -1. php
Encapsulation Inheritance Polymorphism
Encapsulation Data members are normally set inaccessible from outside Data members the class (as well as certain types of methods) protecting methods them from the rest of the script and other classes. This protection of class members is known as encapsulation e. g. <? php. . $dog. Robot = new Robot(); Robot() $dog. Robot ->crawl. Web(); $dog. Robot -> play(); echo $dog. Robot ->talk(); . . . ? >
Inheritance New classes can be defined very similar to existing ones. New classes existing ones All we need to do is specify the differences between the new class and the existing one. Data members and methods which are not defined as Data members being private to a class are automatically accessible by private the new class. This is known as inheritance and is an extremely powerful and useful programming tool.
Polymorphism A concept where a number of related classes all have a related classes method, which shares the same name. method class Fish { draw(). . . //draws a fish. . . } class Dog { draw(). . . //draws a dog. . . } class Bird { draw(). . . //draws a bird. . . } We can write a generic code that can operate on any of can operate on any these classes, invoking the appropriate draw() method draw() based on certain conditions.
Defining a Class
Example: Defining classes class Shopping. Cart { private $name; // Name of shopper private $items; // Items in our shopping cart public function Shopping. Cart($inputname) { Shopping. Cart $this->name = $inputname; } // Add $num articles of $artnr to the cart public function add. Item($artnr, $num) { add. Item $this->items[$artnr] += $num; } // Take $num articles of $artnr out of the cart public function remove. Item($artnr, $num) { remove. Item if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } elseif ($this->items[$artnr] == $num) { unset($this->items[$artnr]); return true; } else { return false; } Let’s examine the syntax of defining a class next. . . } }
Data Members and Methods
Data members and Methods class Class 1 { Class 1 private $str. Name = “A”; $str. Name private $int. Number = 1; $int. Number function get. Name() { } } We need to provide accessor functions to allow users of Class 1 to access the private data members: function get. Number(){ get. Number() function get. Name(){ get. Name() } return $this->str. Name; str. Name } Is this publicly accessible?
$this object pointer As with so many languages, there is a special pointer that references an instance of a class: $this function get. Name(){ return str. Name; return $this->str. Name; } }
Invoking methods inside a class $this->function. Name(); class Person{ . . . function set. Firstname($str. Surname) { $this->str. Firstname = $str. Surname; } function set. Surname($str. Surname) { $this->str. Surname = $str. Surname; } private function display() { echo "<p>Firstname: ". $this->str. Firstname . "</p>"; echo "<p>Surname: ". $this->str. Surname. "</p>"; } function set. Display. Firstname. Surname($str. Firstname, $str. Surname) { $this->set. Firstname($str. Firstname); $this-> $this->set. Surname($str. Surname); $this->display(); $this-> } } Example 16 -4. php
Access Specifiers
Classes class My. Class. Name{ My. Class. Name. . methods. . data members } Visibility of a method or data member: Public Protected Private By default, without By default the access specifiers, class members are class members defined public
Private Access Specifier class My. Class. Name{ My. Class. Name private $str. First. Name; } private – limits the visibility of the methods and data members only to the class that defines them.
Modifying data members int. Number is int. Number private Outside the class, trying to execute the following: $cl. My. Obj->int. Number++; int. Number++ will fail!. . . We need a method to access and change its value: function set. Number($int. Number) { $this->int. Number = $int. Number; } Look at the position of the dollar sign ($) – no longer attached to the variable name
Public Access Specifier class My. Class. Name{ My. Class. Name public $str. First. Name; public function get. First. Name(){ get. First. Name() } } public – class public members can be accessed both within and outside the class. and outside
Protected Access Specifier Class My. Class. Name{ My. Class. Name //protected for public use, but accessible in a derived class protected $str. First. Name; protected function get. First. Name(){ protected get. First. Name() } } Inherited protected class members – class members accessible inside a derived class Visibility of protected class members outside the class definition – protected class members definition are inaccessible.
Examples: Access Specifiers
Access Specifiers PROPERTY DECLARATION
Example: Access Specifiers <? php class My. Class { public $public = 'Public'; protected $protected = 'Protected'; //protected for public use, but accessible in a derived class private $private = 'Private'; function print. Hello() { print. Hello() echo $this->public; echo $this->protected; echo $this->private; } } // outside the class definition $obj = new My. Class(); echo $obj->public; // Works echo $obj->protected; // Fatal Error echo $obj->private; // Fatal Error $obj->print. Hello(); // Shows Public, Protected and Private //. . . http: //php. net/manual/en/language. oop 5. visibility. php
Example: Access Specifiers a Derived class <? php //. . . class My. Class 2 extends My. Class { // We can redeclare the public and protected method, but not private // protected – ‘protected’ for public use, but accessible in a derived class protected $protected = 'Protected 2'; function print. Hello() { echo $this->public; echo $this->protected; echo $this->private; } } // outside the class definition $obj 2 = new My. Class 2(); echo $obj 2 ->public; // Works echo $obj 2 ->private; // Undefined echo $obj 2 ->protected; // Fatal Error $obj 2 ->print. Hello(); // Shows Public, Protected 2, Undefined ? > http: //php. net/manual/en/language. oop 5. visibility. php
Access Specifiers METHOD DECLARATION
Example: Method Declaration <? php class My. Class { // Declare a public constructor public function __construct() { } // Declare a public method public function My. Public() { } //OUTSIDE THE CLASS DEFINITION. . . $myclass = new My. Class; $myclass->My. Public(); // Works $myclass->My. Protected(); // Fatal Error $myclass->My. Private(); // Fatal Error $myclass->Foo(); // Public, Protected and Private work //. . . // Declare a protected method protected function My. Protected() { } // Declare a private method private function My. Private() { } // This is public function Foo() { $this->My. Public(); $this->My. Protected(); $this->My. Private(); } } http: //php. net/manual/en/language. oop 5. visibility. php
Example: Method Declaration <? php class My. Class { // Declare a public constructor public function __construct() { } // Declare a public method public function My. Public() { } // Declare a protected method protected function My. Protected() { } // Declare a private method private function My. Private() { } // This is public function Foo() { $this->My. Public(); $this->My. Protected(); $this->My. Private(); } } class My. Class 2 extends My. Class { // This is public function Foo 2() { $this->My. Public(); $this->My. Protected(); $this->My. Private(); // Fatal Error } } $myclass 2 = new My. Class 2; $myclass 2 ->My. Public(); // Works $myclass 2 ->Foo 2(); // Public and Protected work, not Private http: //php. net/manual/en/language. oop 5. visibility. php
Example: Method Declaration <? php class Bar { public function test() { $this->test. Private(); $this->test. Public(); } public function test. Public() { echo "Bar: : test. Publicn"; } private function test. Private() { echo "Bar: : test. Privaten"; } } $my. Foo = new foo(); $my. Foo->test(); // Bar: : test. Private // Foo: : test. Public ? > class Foo extends Bar { public function test. Public() { echo "Foo: : test. Publicn"; } private function test. Private() { echo "Foo: : test. Privaten"; } } http: //php. net/manual/en/language. oop 5. visibility. php
Accessing Private Members of the same object type <? php class Test { private $foo; public function __construct($foo) { $this->foo = $foo; } private function bar() { echo 'Accessed the private method. '; } Objects of the same type will have access to each others Private and protected members even though they are not the same instances. string(5) "hello" Accessed the private method public function baz(Test $other) { // We can change the private property: $other->foo = 'hello'; var_dump($other->foo); // We can also call the private method: $other->bar(); } } $test = new Test('test'); $test->baz(new Test('other')); ? > http: //php. net/manual/en/language. oop 5. visibility. php
Constructors Destructors
Creating objects • Instantiate classes using new keyword –$my. Cart= new Shopping. Cart(“Charlie”); Constructors –In earlier versions of PHP (< PHP 5. 3. 3) Same as the PHP 5. 3. 3 name of the class. This no longer holds! – (PHP 5 only) declared as PHP 5 only • public function __construct(…) Destructors –Declared as –public function __destruct()
22 Sept. 2010 Latest in PHP 5. 3. 3 <? php namespace Foo; class Bar { public function Bar() { // treated as constructor in PHP 5. 3. 0 -5. 3. 2 // treated as regular method in PHP 5. 3. 3 } } ? >
Constructors A constructor is a function that does initializations when the class is instantiated function __construct($int. Number, $str. Name ){ __construct( $this->set_int. Number($int. Number); $this->set_str. Name($str. Name); $this->print. Init(); //use this method }
Constructors Default arguments function __construct ($str. Name = “A”, $int. Number=0) { $this->set_int. Number($int_Number); $this->set_str. Name($str_Name); } Instantiating a class without parameters will make use of the default values
Another Example: Constructors <? php class vehicle { private $str. Description; function get. Description() { return $this->str. Description; } function set. Description($str. Description) { $this->str. Description = $str. Description; } function __construct ($str. Description) { $this->str. Description = $str. Description; } } ? > vehicle. php
Another Example: Constructors <? php require_once("vehicle. php"); $obj. Bike = new vehicle("Bicycle"); echo "<p>Vehicle: ". $obj. Bike->get. Description(). "</p>"; ? > example 16 -7. php
Destructors Called when objects are destroyed – free up memory e. g. : function __destruct () { echo “freeing up memory, destroying this object. . . ”; } This sample code above simply informs us that the object is being destroyed already.
Objects as variables Can be used in arrays Can be passed to functions Passed as reference all the time (PHP 5) Passed as reference e. g. : function test 1($obj. Class 1){ $obj. Class 1 ->set_int. Name(“B”); } No need to use & in the formal parameter definition. It is always passed by reference. definition.
Arrays and objects <? php function __autoload($class_name) { require_once $class_name. '. php'; } $obj. Simon = new revisedperson("Simon", "Stobart"); $obj. Liz = new revisedperson("Liz", "Hall"); $obj. Ian = new revisedperson("Ian", "Walker"); $obj. Billy = new revisedperson("Billy", "Lee"); $obj. Hayley = new revisedperson("Hayley", "West"); $arr. People = ); $arr. People array($obj. Simon, $obj. Liz, $obj. Ian, $obj. Billy, $obj. Hayley array( foreach($arr. People as $obj. The. Person){ $arr. People echo($obj. The. Person->display()); display() } ? > example 16 -9. php The function display() is common to all array elements display() (elements = objects in this example).
Multiple Object Instances <? php $cart 1 = new Shopping. Cart(“Joe Bloggs”); $cart 1 ->add. Item("10", 1); $cart 2 = new Shopping. Cart(“Fred Smith”); $cart 2 ->add. Item("0815", 3); ? >
Example: Polymorphism <? php function __autoload($class_name) { require_once $class_name. '. php'; } $obj. Rectangle = new rectangle(100, 50, "rectangle. gif"); $obj. Square = new square(100, "square. gif"); $obj. Triangle = new triangle(50, 100, "triangle. gif"); $obj. Ellipse = new ellipse(50, 100, "ellipse. gif"); $arr. Shapes = array ($obj. Rectangle, $obj. Square, $obj. Triangle, $obj. Ellipse); foreach ($arr. Shapes as $obj. Shape){ $obj. Shape->display(); $obj. Shape->area(); } ? > Example 17 -5. php The functions area() and display() are common to all array elements, but executes a different formula for each type of object.
Multiple Source Files • Recommended: Create one PHP source file per class definition. • This aids class reuse and script clarity.
Remember these PHP Constructs? • require(…. ) Includes file specified, terminates on errors • include(…) Includes file specified, gives warning on errors • require_once(…. ) Includes file specified only if it has not already been included, terminates on errors • include_once(…. ) Includes file specified only if it has not already been included, gives warning on errors Really useful but would require you to write a long list of include() or require() statements at the beginning of each script, one for each class. In PHP 5, this is no longer necessary. You may define an __autoload function! Example 16 -6. php
function __autoload() • The function is invoked automatically each time a class is required but has not been defined. • We can insert this function into our script: function __autoload($class_name) { __autoload require_once $class_name. '. php'; require_once } Note: Class_name = File_name Example 16 -7. php
function __autoload() <? php function __autoload($class_name) { __autoload require_once $class_name. '. php'; } Class definition comes from another file. $obj. Simon = new person; $obj. Simon->set. Display. Firstname. Surname(“Napoleon", “Reyes"); $obj. Bike = new vehicle("Bicycle"); echo "<p>Vehicle: ". $obj. Bike->get. Description(). "</p>"; ? > Example 16 -7. php
Exceptions Like all good OO languages, PHP 5 supports the exception mechanism for trapping and handling “unexpected conditions” unexpected conditions Note: not all exceptions are necessarily errors Exceptions not supported in PHP 4
Exceptions Extend the built-in PHP Exception class with your own exceptions (as in Java) class My. Exception extends Exception { // Redefine the exception so message isn't optional public function __construct($message, $code = 0) { // some code // make sure everything is assigned properly parent: : __construct($message, $code); To generate an exception } // custom string representation of object public function __to. String() { return __CLASS__. ": $this->messagen"; } <? php Throw new My. Exception("Message to display"); My. Exception ? > public function custom. Function() { echo "A Custom function for this type of exceptionn"; } }
Objects can. . . Invoke another Be embedded within another object Support for: Inheritance Scope resolution ( : : operator) Class abstraction (define a class that does not instantiate, use “abstract classname”) classname Polymorphism (same function names with different data / behaviour) '==‘ == to check if two object have the same attributes and values '===‘ === to check if two objects are the same instance of the same class
Advanced OO in PHP 5 has rich OO support (similar to the Java model) PHP is a reflective programming language Single inheritance (multiple inheritance not allowed) Abstract classes and methods Interfaces Names of functions/classes to be invoked do not have to be hard wired See also documentation at www. php. net
Reflection-Oriented Programming Normally, instructions are executed and data is processed; however, in some languages, programs can also treat instructions as data and therefore make data reflective modifications. // without reflection $Foo = new Foo(); $Foo->hello(); // with reflection $f = new Reflection. Class("Foo"); Reflection. Class $m = $f->get. Method("hello"); $m->invoke( $f->new. Instance() ); New in PHP, not properly documented yet! Program execution could be modified at run-time. http: //en. wikipedia. org/wiki/Reflection_(computer_science) http: //nz 2. php. net/manual/en/reflectionclass. newinstance. php
For a complete reference http: //www. php. net
- Slides: 56