Php object orientation and classes


Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Php object orientation and classes

  1. 1. ourRemember our last lecturelast lecture??
  2. 2. Encapsulation, Inheritance, PolymorphismEncapsulation, Inheritance, Polymorphism
  3. 3. • Data membersData members• MethodsMethods
  4. 4. Object OrientationObject OrientationPHPisan Object-Oriented programminglanguageFundamental feature of OO isthe classclassPHPclassessupport− Encapsulation− Inheritance− Polymorphism
  5. 5. What is aWhat is a ClassClass??ClassesClassesSophisticatedSophisticated ‘variable types’‘variable types’Data variables (data membersdata members) and functions(methodsmethods) are wrapped up in a class. Collectively,data members and methods are referred to as classclassmembersmembers.An instanceinstance of a classof a class is known as an objectobject.//defining a new class named Robotclass RobotRobot {{//place class members here...}}
  6. 6. Instantiating a class usingInstantiating a class using newnewOnce a classhasbeen created, any numberany number ofobject instancesof that classcan be created.$dogRobot = newnew Robot()Robot();To invoke methods:− object->->method()e.g.<?php....$dogRobot = newnew Robot()Robot();$dogRobot ->crawlWeb();$dogRobot -> play();echo $dogRobot ->talk();...?>
  7. 7. <?phpclass Person {private $strFirstname = “Napoleon";private $strSurname = “Reyes";function getFirstname() {return $this->strFirstname;}function getSurname() {return $this->strSurname;}}// outside the class definition$obj = newnew Person; // an object of type Personecho "<p>Firstname: " . $obj->getFirstname() . "</p>";echo "<p>Surname: " . $obj->getSurname() . "</p>";?>Defining classesDefining classesData membersMethodsExample16-1.php
  8. 8. EncapsulationEncapsulationData membersData members are normally set inaccessible from outsidethe class (as well as certain types of methodsmethods) protectingthem from the rest of the script and other classes.This protection of class members is known asencapsulationencapsulation. e.g.<?php....$dogRobot = newnew Robot()Robot();$dogRobot ->crawlWeb();$dogRobot -> play();echo $dogRobot ->talk();...?>
  9. 9. InheritanceInheritanceNew classesNew classes can be defined very similar to existing onesexisting ones.All we need to do is specify the differencesdifferences between thenew class and the existing one.Data membersData members and methodsmethods which are notnot defined asbeing privateprivate to a class are automatically accessible bythe new class.This is known as inheritanceinheritance and is an extremely powerfuland useful programming tool.
  10. 10. PolymorphismPolymorphismA concept where a number of related classesrelated classes all have amethodmethod, which shares the same name.class Fish { draw()...draw()... //draws a fish//draws a fish...... }}class Dog { draw()...draw()... //draws a dog//draws a dog...... }}class Bird { draw()...draw()... //draws a bird//draws a bird...... }}We can write a generic code that can operate on anycan operate on any ofthese classes, invoking the appropriate draw()draw() methodbased on certain conditions.
  11. 11. Example:Example: Defining classesDefining classesclass ShoppingCart {private $name; // Name of shoppershopperprivate $items; // Items in our shopping cartItems in our shopping cartpublic function ShoppingCartShoppingCart($inputname) {$this->name = $inputname;}// Add $num articles of $artnr to the cartpublic function addItemaddItem($artnr, $num) {$this->items[$artnr] += $num;}// Take $num articles of $artnr out of the cartpublic function removeItemremoveItem($artnr, $num) {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’sexamine the syntax of defining a classnext...
  12. 12. Data members and MethodsData members and Methodsclass Class1Class1 {private $strName$strName = “A”;private $intNumber$intNumber = 1;function getName()Name() {}function getNumber()getNumber(){}}We need to provideaccessor functionstoallow usersof Class1to accessthe privateprivatedata members:function getName()getName(){return $this->this->strNamestrName;}Isthispublicly accessible?
  13. 13. $this$this object pointerobject pointerAswith so many languages, there isa specialpointer that referencesan instance of a class:− $this$thisfunction getName(){return $this->strName;}function getName(){return strName;} 
  14. 14. Invoking methodsInvoking methods inside a classinside a classclass Person{...function setFirstname($strSurname) {$this->strFirstname = $strSurname;}function setSurname($strSurname) {$this->strSurname = $strSurname;}private function display() {echo "<p>Firstname: " . $this->strFirstname . "</p>";echo "<p>Surname: " . $this->strSurname . "</p>";}function setDisplayFirstnameSurname($strFirstname, $strSurname) {$this->$this->setFirstname($strFirstname);$this->$this->setSurname($strSurname);$this->$this->display();}}$this->$this->functionName();Example16-4.php
  15. 15. ClassesClassesclass MyClassNameMyClassName{ members}Visibility of a methodor data member:− PublicPublic− ProtectedProtected− PrivatePrivate− By defaultBy default, withoutthe accessspecifiers,class membersclass members aredefined publicpublic.
  16. 16. PrivatePrivate Access SpecifierAccess Specifierclass MyClassNameMyClassName{privateprivate $strFirstName;}privateprivate – limitsthevisibility of the methodsand data membersonly to the classthatdefinesthem.
  17. 17. Modifying data membersModifying data membersOutside the class, trying to executethe following:$clMyObj->intNumber++intNumber++;will fail!...We need a method to accessand changeitsvalue:function setNumber($intNumber) {$this->intNumber = $intNumber;}intNumberintNumber is privateprivateLook at the position of the dollar sign ($) – nolonger attached to the variable name
  18. 18. PublicPublic Access SpecifierAccess Specifierclass MyClassNameMyClassName{publicpublic $strFirstName;publicpublic function getFirstName()getFirstName(){}} publicpublic – classmemberscan beaccessed both withinwithinand outsideand outside the class.
  19. 19. ProtectedProtected Access SpecifierAccess SpecifierClass MyClassNameMyClassName{protectedprotected $strFirstName;protectedprotected function getFirstName()getFirstName(){}}InheritedInherited protectedprotected class membersclass members –accessible inside a derived classderived classVisibility ofVisibility of protectedprotected class membersclass membersoutside the class definitionoutside the class definition – protectedclassmembersare inaccessible.//protected for public use, but accessible in aderived class
  21. 21. <?phpclass MyClass {public $public = Public;protected $protected = Protected; //protected for public use, but accessible in a derived classprivate $private = Private;function printHello()printHello() {echo $this->public;echo $this->protected;echo $this->private;}}// outside the class definition$obj = new MyClass();echo $obj->public; // Worksecho $obj->protected; // Fatal Errorecho $obj->private; // Fatal Error$obj->printHello(); // Shows Public, Protected and Private//...Example:Example: Access SpecifiersAccess Specifiers
  22. 22. <?php//...class MyClass2 extendsextends MyClass{// We can redeclare the public and protected method, but not private// protected – ‘protected’ for public use, but accessible in a derived classprotected $protected = Protected2;function printHello(){echo $this->public;echo $this->protected;echo $this->private;}}// outside the class definition$obj2 = new MyClass2();echo $obj2->public; // Worksecho $obj2->private; // Undefinedecho $obj2->protected; // Fatal Error$obj2->printHello(); // Shows Public, Protected2, Undefined?>Example:Example: Access SpecifiersAccess Specifiers Derived class
  24. 24. //OUTSIDE THE CLASS DEFINITION...$myclass = new MyClass;$myclass->MyPublic(); // Works$myclass->MyProtected(); // Fatal Error$myclass->MyPrivate(); // Fatal Error$myclass->Foo(); // Public, Protected and Private work//...<?phpclass MyClass{// Declare a public constructorpublic function __construct() { }// Declare a public methodpublic function MyPublic() { }// Declare a protected methodprotected function MyProtected() { }// Declare a private methodprivate function MyPrivate() { }// This is publicfunction Foo(){$this->MyPublic();$this->MyProtected();$this->MyPrivate();}} Method DeclarationMethod Declaration
  25. 25. class MyClass2 extendsextends MyClass{// This is publicfunction Foo2(){$this->MyPublic();$this->MyProtected();$this->MyPrivate(); // Fatal Error}}$myclass2 = newnew MyClass2;$myclass2->MyPublic(); // Works$myclass2->Foo2(); // Public and Protected work, not PrivateExample:Example: Method DeclarationMethod Declaration  <?phpclass MyClass{// Declare a public constructorpublic function __construct() { }// Declare a public methodpublic function MyPublic() { }// Declare a protected methodprotected function MyProtected() { }// Declare a private methodprivate function MyPrivate() { }// This is publicfunction Foo(){$this->MyPublic();$this->MyProtected();$this->MyPrivate();}}
  26. 26. $myFoo = new foo();$myFoo->test(); // Bar::testPrivate// Foo::testPublic?>Example:Example: Method DeclarationMethod Declaration<?phpclass Bar{public function test() {$this->testPrivate();$this->testPublic();}public function testPublic() {echo "Bar::testPublicn";}private function testPrivate() {echo "Bar::testPrivaten";}}class Foo extends Bar{public function testPublic() {echo "Foo::testPublicn";}private function testPrivate() {echo "Foo::testPrivaten";}}
  27. 27. string(5) "hello"Accessed the private methodAccessing Private Members of theAccessing Private Members of thesame object typesame object type<?phpclass Test{private $foo;public function __construct($foo){$this->foo = $foo;}private function bar(){echo 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));?>Objectsof the same type will have accessto each othersPrivate and protected memberseven though they arenot the same instances.
  28. 28. Creating objectsCreating objects•Instantiate classes using new keyword–$myCart= newnew ShoppingCart(“Charlie”);ConstructorsConstructors–In earlier versions of PHP (< PHP5.3.3PHP5.3.3) Same as thename of the class. This no longer holds!This no longer holds!– (PHP5 onlyPHP5 only) declared as•public function __construct(…)DestructorsDestructors–Declared as–public function __destruct()
  29. 29. Latest in PHPLatest in PHP5.<?phpnamespace 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}}?>22 Sept. 2010
  30. 30. ConstructorsConstructorsA constructorconstructor isa function that doesinitializationswhen the classisinstantiatedfunction __construct(__construct($intNumber, $strName)){$this->set_intNumber($intNumber);$this->set_strName($strName);$this->printInit();//use thismethod}
  31. 31. ConstructorsConstructorsDefault argumentsDefault argumentsfunction __construct ($strName = “A”, $intNumber=0) {$this->set_intNumber($int_Number);$this->set_strName($str_Name);}Instantiating a classwithout parameterswillmake use of the default values
  32. 32. Another Example:Another Example: ConstructorsConstructors<?phpclass vehiclevehicle {private $strDescription;function getDescription() {return $this->strDescription;}function setDescription($strDescription) {$this->strDescription = $strDescription;}function __construct ($strDescription) {$this->strDescription = $strDescription;}}?>vehicle.php
  33. 33. Another Example:Another Example: ConstructorsConstructors<?phprequire_once("vehicle.php");$objBike = new vehicle("Bicycle");echo "<p>Vehicle: " . $objBike->getDescription() . "</p>";?>example16-7.php
  34. 34. DestructorsDestructorsCalled when objectsare destroyed – free upmemorye.g.:function __destruct () {echo “freeing up memory, destroying thisobject... <br>”;}This sample code above simply informs us that the object isbeing destroyed already.
  35. 35. Objects as variablesObjects as variablesCan be used in arraysCan be passed to functionsPassed as referencePassed as reference all the time (PHP 55)e.g.:function test1($objClass1){$objClass1->set_intName(“B”);}No need to use && in the formal parameterin the formal parameterdefinition.definition. It isalwayspassed by reference.
  36. 36. Arrays and objectsArrays and objects<?phpfunction __autoload($class_name) {require_once $class_name . .php;}$objSimon = new revisedperson("Simon", "Stobart");$objLiz = new revisedperson("Liz", "Hall");$objIan = new revisedperson("Ian", "Walker");$objBilly = new revisedperson("Billy", "Lee");$objHayley = new revisedperson("Hayley", "West");$arrPeople$arrPeople = array(array($objSimon, $objLiz, $objIan, $objBilly, $objHayley));foreach($arrPeople$arrPeople as $objThePerson){echo($objThePerson->->display()display());}?>The function display()display() is common to all array elements(elements = objects in this example).example16-9.php
  37. 37. Multiple Object InstancesMultiple Object Instances<?php$cart1 = new ShoppingCart(“Joe Bloggs”);$cart1->addItem("10", 1);$cart2 = new ShoppingCart(“Fred Smith”);$cart2->addItem("0815", 3);?>
  38. 38. Example:Example: PolymorphismPolymorphism<?phpfunction __autoload($class_name) {require_once $class_name . .php;}$objRectangle = new rectangle(100,50, "rectangle.gif");$objSquare = new square(100, "square.gif");$objTriangle = new triangle(50,100, "triangle.gif");$objEllipse = new ellipse(50,100, "ellipse.gif");$arrShapes = array ($objRectangle,$objSquare,$objTriangle,$objEllipse);foreach ($arrShapes as $objShape){$objShape->display();$objShape->area();}?>The functions area() and display() are common to all arrayelements, but executes a different formula for each type of object.Example17-5.php
  39. 39. • Recommended: Create one PHPsource file per classdefinition.• Thisaidsclassreuse and script clarity.
  40. 40. Remember these PHP Constructs?Remember these PHP Constructs?• require(….)require(….)− Includesfile specified, terminatesterminates on errors• include(…)include(…)− Includesfile specified, gives warningwarning on errors• require_once(….)require_once(….)− Includesfile specified only if it hasnot already beenincluded, terminatesterminates on errors• include_once(….)include_once(….)− Includesfile specified only if it hasnot already beenincluded, gives warningwarning on errorsExample16-6.phpReally useful but would require you to write a long list of include() or require() statementsat the beginning of each script, one for each class. In PHP5, this is no longernecessary. You may define an __autoload function!
  41. 41. functionfunction __autoload()__autoload()• The function is invoked automatically each time a class isrequired but has not been defined.• We can insert this function into our script:Example16-7.phpfunction __autoload__autoload($class_name) {require_oncerequire_once $class_name . .php;}Note: Class_name = File_name
  42. 42. functionfunction __autoload()__autoload()Example16-7.php<?phpfunction __autoload__autoload($class_name) {require_once $class_name . .php;}$objSimon = newnew person;$objSimon->setDisplayFirstnameSurname(“Napoleon", “Reyes");$objBike = newnew vehicle("Bicycle");echo "<p>Vehicle: " . $objBike->getDescription() . "</p>";?>Classdefinition comesfromanother file.
  43. 43. ExceptionsExceptionsLike all good OO languages, PHP5 supports the exceptionmechanism for trapping and handling “unexpected conditionsunexpected conditions”Note: not all exceptions are necessarily errorsExceptions not supported in PHP4
  44. 44. classclass MyExceptionMyException extendsextends Exception {{// Redefine the exception so message isnt optionalpublic function __construct($message, $code = 0) {// some code// make sure everything is assigned properlyparent::__construct($message, $code);}// custom string representation of objectpublic function __toString() {return __CLASS__ .. ": $this->messagen";}public function customFunction() {echo "A Custom function for this type of exceptionn";}}}Extend the built-in PHP Exception class with your ownExtend the built-in PHP Exception class with your ownexceptions (as in Java)exceptions (as in Java)ExceptionsExceptions<?phpThrow new MyExceptionMyException("Message to display");?>To generate an exception
  45. 45. Objects can...Objects can...Invoke anotherBe embedded within another objectSupport for:− Inheritance− Scope resolution ( :::: operator)− Classabstraction (define a classthat doesnotinstantiate, use “abstractabstract classclass classnameclassname” )− Polymorphism (same function nameswith differentdata / behaviour)− ====‘ to check if two object have the same attributesand values− ======‘ to check if two objectsare the same instance of the same class
  46. 46. Advanced OO in PHPAdvanced OO in PHPPHP5 hasrich OO support (similar to the Java model)− Single inheritance (multiple inheritance not allowed)− Abstract classesand methods− InterfacesPHPisa reflective programming language− Namesof functions/classesto be invoked do not have to be hardwiredSee also documentation at
  47. 47. Reflection-Oriented ProgrammingReflection-Oriented Programming// without reflection// without reflection$Foo = new Foo();$Foo->hello();// with reflection// with reflection$f = new ReflectionClassReflectionClass("Foo");$m = $f->getMethod("hello");$m->invoke( $f->newInstance() );Normally, instructions areexecuted and data isprocessed; however, in somelanguages, programs canalso treat instructions asinstructions asdatadata and therefore makereflective modifications. execution couldbe modified at run-time.New in PHP, not properlydocumented yet!
  48. 48. For a complete reference