PHP Tutorials Examples Object Oriented Programming with PHP

http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP...

Login or Register Now Email:

Password:

Home

Tutorials

Articles

Examples

Projects

Classes

Manual

Contact

Object Oriented Programming with PHP
by Kevin Waterson

Support PHPRO.ORG

Draft Only
Contents What is OOP What is an Object What is a class Commenting code Inheritance (Extending a class) Visibility (public, private, protected) Final Abstract Classes Static Methods and properities Interfaces PHP Class Functions get_declared_interaces() get_class()

Search

Web

www.phpro.org

PHPRO.ORG Poll

When programming, do you prefer:
Caffeine Weed Alcohol Barbituates Opiates All of the above Warning: Participation in PHPRO.ORG polls may incorrectly lead you to believe your opinions matter. RSS Feed

class_exists() get_declared_classes() Autoload Serializing Objects Overloading Class Constants Credits

What is OOP
OOP was first invented for the purpose of physical modelling in the Simula-67. Whilst there is no hard and fast definition of what Object Oriented Programming (OOP) is, we can define. So lets just use this loose definition for now and it is left to reader to make up their own minds about what a decent definition is. Object Oriented Programming (OOP) is a programming concept that treats functions and data as objects. OK, not the best definition but gives us an opening. The key word here is objects. As we progress through this tutorial we will see how data and functions can be represented as re-usable objects, thus cutting down on code and time.

What is an Object
Simply put, an oject is a bunch of variables and functions all lumped into a single entity. The object can then be called rather than calling the variables or functions themselves. Within an object there are methods and properties. The methods are functions that manipulate data withing the object. The properties are variables that hold information about

1 of 24

6/19/2013 4:46 PM

PHP Tutorials Examples Object Oriented Programming with PHP

http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP...

the object.

What is a Class
A class is the blueprint for your object. The class contains the methods and properties, or the charactaristics of the object. It defines the object. Lets just start with some examples to see how it all pieces together. We will use a vehicle as our object. All vehicles share similar charactaristics, eg: number of doors, they are painted some color, they each have a price. All vehicles do similar things also, drive, turn left, turn right, stop etc. These can be described as functions, or in OOP parlance, methods. So, the class holds the definition, and the object holds the value. You declare class in PHP by using the class keyword.

<?php class vehicle{ /*** define public properties ***/

/*** the color of the vehicle ***/ public $color;

/*** the number of doors ***/ public $num_doors;

/*** the price of the vehicle ***/ public $price;

/*** the shape of the vehicle ***/ public $shape;

/*** the brand of vehicle ***/ public $brand;

/*** the constructor ***/ public function __construct(){ echo 'About this Vehicle.<br />'; }

/*** define some public methods ***/

/*** a method to show the vehicle price ***/ public function showPrice(){ echo 'This vehicle costs '.$this->price.'.<br />'; }

/*** a method to show the number of doors ***/ public function numDoors(){ echo 'This vehicle has '.$this->num_doors.' doors.<br />'; }

/*** method to drive the vehicle ***/ public function drive(){ echo 'VRRROOOOOOM!!!'; }

} /*** end of class ***/ ?> With this simple class definition we can now create one, or many, vehicle objects. Lets see how its done, then we will step through it all. To create a new object from the class definition we use the new keyword.

<?php

2 of 24

6/19/2013 4:46 PM

/*** cost of the vehicle ***/ $vehicle->price = 100000.org/tutorials/Object-Oriented-Programming-with-PHP. or as they are known in the OOP world. Lets step through the class definition first to see what its all about. /*** number of doors ***/ $vehicle->num_doors = 2. This vehicle has 2 doors. About this vehicle. ?> Using the combination of the two code boxes above.PHP Tutorials Examples Object Oriented Programming with PHP http://www. /*** the number of doors ***/ public $num_doors. /*** the brand of vehicle ***/ $vehicle->brand = 'Porsche'.. /*** call the numDoors method ***/ $vehicle->numDoors().. /*** the color of the vehicle ***/ $vehicle->color = 'Red'. /*** create a new vehicle object ***/ $vehicle = new vehicle. <?php /*** the color of the vehicle ***/ public $color. We began the class with the class keyword. /*** the price of the vehicle ***/ public $price.. /*** call the showPrice method ***/ $vehicle->showPrice(). properties. you should have something like. <?php class vehicle{ ?> Next we declared some variables. /*** drive the vehicle ***/ $vehicle->drive(). This tells PHP that what follows is a class definition.phpro. /*** the shape of vehicle ***/ $vehicle->shape = 'Coupe'. This vehicle costs 100000. /*** the shape of the vehicle ***/ public $shape. 3 of 24 6/19/2013 4:46 PM . /*** the brand of vehicle ***/ public $brand.

Following on from the class definition we see our userland code. Next in the class definition is this code. our methods are similar to normal PHP functions. If a class needs to do something before running some code. However you may note the use of variables like $this->price and $this->num_doors. of our vehicle class. then this is the place to do it. Following the constructor is several methods (functions) that do things. <?php /*** create a new vehicle object ***/ $vehicle = new vehicle.$this->price.phpro. The public declares that this property may be accessed within the public scope. or new object. It is often used to set properties within the class.$this->num_doors. As mentioned earlier we do this with the use of the new keyword. } ?> The constructor method (function) is a special function that is executed every time a new object is created or "instantiated". ?> The properties are the individual charactaristics of the vehicle object. It is at this time that the constructor is called and any code within the constructor is executed.<br />'.<br />'. <?php 4 of 24 6/19/2013 4:46 PM .<br />'. This is the code we use to instantiate (create) a new instance. } /*** method to drive the vehicle ***/ public function drive(){ echo 'VRRROOOOOOM'. } ?> As you see above.' doors.. You may pass a variable directly to the constructor from your code.'. so it cannot be used as a variable or property name. The keyword $this is used to refer to properties or methods within the class itself.PHP Tutorials Examples Object Oriented Programming with PHP http://www. This means you may set it from within your code. <?php /*** the constructor ***/ public function __construct(){ echo 'About this vehicle. } /*** a method to show the number of doors ***/ public function numDoors(){ echo 'This vehicle has '. but more of that later.. I like to put a comment beside it so I dont delete it or get it confused with a function I am writing. ?> The code above creates a new object from our class definition called $vehicle. These methods are also preceded by the public meaning they are available with the scope of your code.org/tutorials/Object-Oriented-Programming-with-PHP.. Finally we finished our class definition with a closing }. <?php /*** a method to show the vehicle price ***/ public function showPrice(){ echo 'This vehicle costs '. The $this keyword is reserved in PHP. Once we have a new object we can then begin to assign values to the properties of that object as seen here.

followed by the parameter it takes. You see how easy it would be now to create a new car object. /*** the color of the vehicle ***/ $vehicle->color = 'Red'.phpro.. An example follows below.org/tutorials/Object-Oriented-Programming-with-PHP.PHP Tutorials Examples Object Oriented Programming with PHP http://www. although some may find it excessive. <?php /*** call the showPrice method ***/ $vehicle->showPrice(). /*** the brand of vehicle ***/ $vehicle->brand = 'Porsche'. It is good practice to show what these arguements are and there types. but shows well the commenting of code. We can also see within the function itself a single line 5 of 24 6/19/2013 4:46 PM . This is a good practice. rather than echo a line of HTML code. } ?> The above function is rather simplistic. thats the step-by-step of your first class. Most methods within a class will return a value. OOP can get very abstracted and if you are not careful it is easy to lose site of your programmatical work flow. /*** call the numDoors method ***/ $vehicle->numDoors(). Finally the comment block tells us that the return value is of type INT. /*** the shape of vehicle ***/ $vehicle->shape = 'Coupe'. It tells us that access to the function is private (more on this in the next section). ?> So. The comments begin in a block of C type multiline comments and gives us a brief description of what it does.000. as it may not be you who has to edit the code next time. A class method may also take one. /*** drive the vehicle ***/ $vehicle->drive(). it is now simple to use the object methods to manipulate the object by calling the methods. in this case an array of numbers. Perhaps a Red Ferrari with 4 doors costing $250. arguements. <?php /** * adds an array of numbers and returns the value * * @param array $numbers An array of numbers to add * * @access private * * @return int Returns sum of numbers * */ private function sum_of_numbers($numbers){ /*** return the sum of the $numbers array ***/ return array_sum($numbers). or several.00. /*** number of doors ***/ $vehicle->num_doors = 2. Commenting Code In the previous sections you have seen comments for almost every line of code.. ?> With the properties set as above. The methods are executed like this below.

PHP Tutorials Examples Object Oriented Programming with PHP http://www.class. A motorcycle is still a vehicle and shares many of the same attributes such as price.class. } /** * 6 of 24 6/19/2013 4:46 PM .php'). /** * * set the type of handlebars * * @access public * * @param string * * @return string * **/ public function setHandlebars($handlebarType){ $this->handlebars=$handlebarType. But a motorcycle has some unique features that a car does not. <?php /*** include the vehicle class definition ***/ include('vehicle.. It is important here to note the naming convention here as it will be important later in this tutorial. plus whatever is in the new child. drive etc. The resulting object of an extend class has all the charactaristics of the parent class. Rather than type out the whole of the vehicle class definition again. class motorcycle extends vehicle{ /*** the number of side cars ***/ private $num_sidecars. private $handlebars. } /** * * Set number of side cars * * @access public * * @param int * * @return int * **/ public function setSidecar($numSidecars){ $this->numSidecars = $numSidecars. Inheritance (Extending a class) Probably the greatest feature of the PHP OOP model is Inheritence. we will save it in a file of its own called vehicle.phpro. Inheritence is the ability of php to extend classes (child classes) that inherit the charactaristics of the parent class. or extended class..org/tutorials/Object-Oriented-Programming-with-PHP. If you follow these practices you code will always be readable and easy to follow by yourself and others.php. In this instance we will extend the vehicle class and add a motorcyle. Lets see how it works. comment just to show what is happening within the funtion itself.

* Show the numbers of sidecars * * @return string * **/ public function showSideCar(){ echo 'This motorcyle has '.. /*** show the sidecars ***/ $vehicle->showSideCar(). Either as code.org/tutorials/Object-Oriented-Programming-with-PHP.': '.'<br />'. ?> You see in the motorcycle class that we have used the keyword extends to extend our vehicle class.phpro. /*** the color of the vehicle ***/ $vehicle->color = 'Black'. or most 7 of 24 6/19/2013 4:46 PM . /*** call the showPrice method ***/ $vehicle->showPrice(). you must include the class file.php on line 3 You MUST include the class definition on *every page* when you store an object This means when you use an object or wish to extend from it. } } /*** end of class ***/ /*** our userland code ***/ /*** create a new vehicle object ***/ $vehicle = new motorcycle. /*** number of doors ***/ $vehicle->num_doors = 0. /*** drive the vehicle ***/ $vehicle->drive(). /*** show the vehicle brand and type ***/ echo $vehicle->brand. /*** cost of the vehicle ***/ $vehicle->price = 25000. /*** set the sidecar ***/ $vehicle->setSidecar(1). /*** type of handle bars ***/ $vehicle->setHandlebars('Ape Hangers'). you will get a Fatal Error like this: Fatal error: Class 'vehicle' not found in /www/oop. /*** the shape of vehicle ***/ $vehicle->shape = 'Sportster'. The child class has inherited all the characaristics of the parent vehicle class.$vehicle->shape. /*** the brand of vehicle ***/ $vehicle->brand = 'Harley Davidson'.. If you run the above code with out including the parent class.' sidecar<br />'.PHP Tutorials Examples Object Oriented Programming with PHP http://www. We can then proceed to set vars in the both the parent class and the child class. $this->numSidecars.

. private. It is private to the calling class. methods). /*** set the value of the number ***/ $math->num = 2. <?php class mathematics{ /*** a number ***/ public $num. A could arise if we lost track of our values and changed the value of $num. Public class members (properties and methods) are available through-out the script and may be accessed from outside the class as we demonstrated in our car class. It is good practice to declare the visibility of class members for the sake of readability for yourself and others. /*** call the addTwo method ***/ echo $math->addTwo(). ?> We can see in the above example that the public variable $num is set from user space and we call a public method that adds two the number and returns the value of $num+2.phpro. It is much easier for another programmer to see your intentions. Even with this in place it is still possible for somebody to simply access the $num variable. This means if you do not declare a property or method within the class. So we make the variable private. } }/*** end of class ***/ /*** Instantiate a new class instance ***/ $math = new mathematics. Visibility (public. To counter this problem we can create a method to set the value for us. Three levels of visibilty exist for class members. all class members are public. protected) The visibility of class members. This will also future proof your scripts should access modifiers be deprecated. This ensures us that the property is only available within the class itself. but it can also work against us. or accessible from any part of our script works in our favour here. <?php 8 of 24 6/19/2013 4:46 PM . (properties.org/tutorials/Object-Oriented-Programming-with-PHP. it will be public. with an include() statement. Consider the following code. commonly. relates to how that member may be manipulated within. or from outside the class.. public private protected By default. Lets create a simple new class to demonstrate. /** * * Add two to a number * * @access public * * @return int * **/ public function addTwo(){ return $this->num+2.PHP Tutorials Examples Object Oriented Programming with PHP http://www. Having our properties (variables) visible.

/** * * Set the value of $num * * @access public * * @param $num The number to set * * @return int * **/ public function setNum($num){ $this->num = $num. class mathematics{ /*** a number ***/ private $num. But unlike private.PHP Tutorials Examples Object Oriented Programming with PHP http://www. } }/*** end of class ***/ /*** Instantiate a new class instance ***/ $math = new mathematics.. <?php class mathematics{ /*** a number ***/ 9 of 24 6/19/2013 4:46 PM . This is because private methods and properties in a parent class are not visible to child classes and cannot be accessed.org/tutorials/Object-Oriented-Programming-with-PHP.phpro.php on line 43 Even if you were to try to access the private $num property from a child class it would fail..class. } /** * * Add two to a number * * @access public * * @return int * **/ public function addTwo(){ return $this->num+2. protetected methods and properties are available only to the class that created them. /*** set the value of the number ***/ $math->setNum(2). Like the private keyword. To access a parent method or property from a child class you need to use the protected keyword. Lets see how this works. /*** call the addTwo method ***/ echo $math->addTwo(). protected methods and properties are visible from a parent class. ?> ?> Any further attempt to reset the $num property without the setNum() method would result in a Fatal Error such as Fatal error: Cannot access private property mathematics::$num in /www/mathematics.

} /** * * Add two to a number * * @access public * * @return int * **/ public function addTwo(){ return $this->num+2. /*** return the new number and round to 2 decimal places ***/ return round($new_num.PHP Tutorials Examples Object Oriented Programming with PHP http://www. ?> 10 of 24 6/19/2013 4:46 PM .. /*** set the value of the number ***/ $math->setNum(14).. /** * * Set the value of $num * * @access public * * @param $num The number to set * * @return int * **/ public function setNum($num){ $this->num = $num. 2). protected $num.phpro. } }/*** end of class ***/ class divide extends mathematics{ /** * * Divide a number by two * * @access public * * @return int * **/ public function divideByTwo(){ /*** divide number by two ***/ $new_num = $this->num/2. echo $math->divideByTwo().org/tutorials/Object-Oriented-Programming-with-PHP. } } /*** end of class ***/ /*** Instantiate a new class instance ***/ $math = new divide.

Lets put it to the test. This ensures that the implementation is correct. As you can see. You cannot create a new object from it. in turn. you must also declare the class itself as abstract too. If this is not done a fatal error is generated.phpro. So. <?php final class mathematics{ } /*** end of class ***/ class divide extends mathematics{ } ?> By running the above code you will get an error such as Fatal error: Class divide may not inherit from final class (mathematics) in /www/final. Abstract Classes An abstract class is a class that cannot be instantiated on its own.. Any method or class that is declared as Final cannot be overridden or inherited by another class. Another way of protecting yourself is the Final keyword. whats the point you ask? Well.php on line 23. you can inherit from an abstract class. To see this lets make a basic class. Any class that extends an abstract parent class must create an interface of the parent abstract methods. you will get an error something like this Fatal error: Cannot instantiate abstract class mathematics in /www/abstract. <?php abstract class mathematics{ /** * * Add two to a number * * @access public * * @return int * **/ public function addTwo(){ return $this->num+2. Also if you declare any class method to be abstract. We are able to do this because the $num property has been declared protected and is visible to the child class. 11 of 24 6/19/2013 4:46 PM .org/tutorials/Object-Oriented-Programming-with-PHP. } } /*** end of class ***/ /*** try to create new object from the mathematics class ***/ $math = new mathematics ?> Using the code above.PHP Tutorials Examples Object Oriented Programming with PHP http://www.php on line 8 This can protect us from those who wish to use our code for a purpose other than that for which it was intended.. We can see here the the user space code has called the setNum() method in the parent mathematics class. Final As we saw in the previous section there are ways to protect your code from being used in an improper manner. sets the $num property. This method. this is not allowed.

The static declaratin must come after the visibility declaration.org/tutorials/Object-Oriented-Programming-with-PHP. <?php abstract class mathematics{ /*** child class must define these methods ***/ abstract protected function getMessage(). /*** do the math ***/ echo $myMath->addTwo(4).. abstract protected function addTwo($num1). /** * * method common to both classes * **/ public function showMessage() { echo $this->getMessage(). } } /*** end of class ***/ class myMath extends mathematics{ /** * * Prefix to the answer * * @return string * **/ protected function getMessage(){ return "The anwser is: ".PHP Tutorials Examples Object Oriented Programming with PHP http://www. ?> Static Methods and Properties The use of the static keyword allows class members (methods and properties) to be used without needing to instantiate a new instance of the class.phpro.. eg: 12 of 24 6/19/2013 4:46 PM . } /** * * add two to a number * * @access public * * @param $num1 A number to be added to * * @return int * **/ public function addTwo($num1) { return $num1+2. /*** show the message ***/ $myMath->showMessage(). } } /*** end of class ***/ /*** a new instance of myMath ***/ $myMath = new myMath.

13 of 24 6/19/2013 4:46 PM . the keyword $this and the arrow operator. Lets whip up a quick example of using static. /*** echo the new count ***/ echo counter::getCount().phpro. so lets use something practical. '<br />'.'<br />'. Static variables belong to the class itself and not to any object of that class. Here we will use a basic counter class. duh **/ function __construct() { self::$count++. } /** give the static variable a value ***/ myClass::$foo = 'Bar'. <?php class counter{ /*** our count variable ***/ private static $count = 0. -> are not available. /*** get the count ***/ echo counter::getCount() . public static myClass{ Because there is no object created when using a static call. /** * Constructor. To access withing the class itself you need to use the self keyword along with the :: scope resolution operator. Static properties are often used as counters. /*** echo the static variable ***/ echo (myClass::$foo ). /*** create another instance ***/ $next = new counter(). <?php /*** a simple class ***/ class myClass{ /*** a static variable ***/ static $foo. } } /*** end of class ***/ /*** create a new instance ***/ $count = new counter().. } /** * * get the current count * * @access public * * @return int * **/ public static function getCount() { return self::$count. ?> The above snippet will echo Bar This is rather basic as an example.PHP Tutorials Examples Object Oriented Programming with PHP http://www.org/tutorials/Object-Oriented-Programming-with-PHP..

An interface cannot be instantiated on its own. Interfaces make this a much easier process. Here we will demonstrate how this works using our vehicle class from earlier.. with the addition of a stop() function. Not also the use of the :: scope resolution operator and self keyword to refer to the static variable within the class itself. Interfaces Interfaces in PHP allow you to define a common structure for your classes. } /*** define some public methods ***/ /*** a method to show the vehicle price ***/ public function showPrice(){ echo 'This vehicle costs '. echo counter::getCount(). } /*** a method to show the number of doors ***/ public function numDoors(){ echo 'This vehicle has '. } /*** method to drive the vehicle ***/ public function drive(){ echo 'VRRROOOOOOM!!!'.phpro.' doors.<br />'. or classes. One of the goals of OOP is re-use of code.$this->price.org/tutorials/Object-Oriented-Programming-with-PHP. /*** and a third instance ***/ $third = new counter.'<br />'.. ?> Hopefully by the end of the above snippet you can see what is happening. <?php class vehicle implements testdrive{ /*** define public properties ***/ /*** the color of the vehicle ***/ public $color. /*** the brand of vehicle ***/ public $brand.'.<br />'. /*** the shape of the vehicle ***/ public $shape. At each new instance the counter class we increment by one. they are simply a "mapping" or constraint of what the class.PHP Tutorials Examples Object Oriented Programming with PHP http://www. The interface methods have no internal logic.$this->num_doors. } /** * a method to stop the car * * @access public * 14 of 24 6/19/2013 4:46 PM . /*** the constructor ***/ public function __construct(){ echo 'About this Vehicle. /*** the price of the vehicle ***/ public $price.<br />'. /*** the number of doors ***/ public $num_doors. should implement.

?> You may of course create multiple classes to implement your interface. If we had two classes. one for a fax and the other for a printer. public function send(). } ?> Both of the above classes give the required usage for each item. **/ public function stop(){ echo 'SSSCCRRREEEEEECCHH!!!<br />'. In contrast. To get the usage of both classes we would do something like this: <?php class fax{ public function dial(). In the real world interfaces provide us with the tools harness parts of multiple classes. 15 of 24 6/19/2013 4:46 PM .PHP Tutorials Examples Object Oriented Programming with PHP http://www. } class printer{ public function printBlack(). you may choose to override some of parent methods. public function printColor(). public function printDraft(). /*** call some methods ***/ $object->drive(). If you had multiple parent class methods with the same name. When you inherit from a parent class.org/tutorials/Object-Oriented-Programming-with-PHP. public function send(). classes that implement an interface. } /*** an new vehicle object ***/ $object = new vehicle. public function recieve(). public function printDraft(). } } /*** end of class ***/ /*** declare our interface ***/ interface testdrive{ /*** some functions that must be implemented ***/ function drive(). Consider this scenario. function stop(). } class printer extends fax{ public function printBlack(). $object->stop().. PHP would have no way of telling which of these methods to use. but they do not take into consideration the existance of a printer/fax machine. This is why multiple inheritance does not work in PHP. public function printColor(). but different functionality or charactaristics. but they will not inherit from each other.. must implement every method so there is no ambiguity.phpro. Each has seperate uses and could be described like this: <?php class fax{ public function dial(). public function recieve().

Then the printer class extends the fax class and inherits all the methods from that class. <?php interface fax{ public function dial(). } interface printer{ public function printBlack(). printer{ public function dial(){ } public function send(){ } public function recieve(){ } public function printBlack(){ } public function printColor(){ } public function printDraft(){ } public function kick(){ } } $object = new printerFax. It will produce no output but we need to be sure all is well. public function send(). Having run the code.. Interfaces play a major role in with SPL and it is recommend you implement the interfaces from SPL and not just the class methods. ?> This code works by creating a stack of classes. What you should now get is an error such as: Fatal error: Class printerFax contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (printer::kick) in /www/oop. but we MUST have them all or we will get errors such as the one above.php on line 22 With the kick() function removed from our implementation. The grandparent class is fax. public function kick(). get_declared_interfaces() 16 of 24 6/19/2013 4:46 PM . public function recieve(). PHP Class functions PHP has available several class functions to help you through the OOP mine field. } class printerFax extends fax{ } $object = new printerFax. } class printerFax implements fax. remove the line public function kick(){ } and run it again. public function printColor(). Lets look at the design. The printer class now has the function dial() available to it which is clearly going to cause some confusion and possibly errors in logic. To counter this problem an interface can be used to tell the classes what functions (methods) are required. public function printDraft(). it is recommended you run the above code.. We can gather these functions fractionally from multiple classes.PHP Tutorials Examples Object Oriented Programming with PHP http://www. public function kick().phpro. This is where some problems may arise. we have essentially broken the contract that says we will implement every function (method) specified in the interface.org/tutorials/Object-Oriented-Programming-with-PHP. ?> Before we go further.

} interface printer{ public function printBlack(). <?php interface fax{ public function dial(). } /*** our interface implementation ***/ class printerFax implements fax. get_declared_interfaces() This helper function provides an array of all the available declared interfaces. public function recieve(). '.org/tutorials/Object-Oriented-Programming-with-PHP. class_exists() get_class() get_declared_classes() Each of these is shown here beginning with the get_declared_interfaces().phpro. The 17 of 24 6/19/2013 4:46 PM . /*** get the declared interfaces ***/ foreach(get_declared_interfaces() as $key=>$interface) { echo $key.PHP Tutorials Examples Object Oriented Programming with PHP http://www.. } ?> The above code should produce a list such as this: 0 => Traversable 1 => IteratorAggregate 2 => Iterator 3 => ArrayAccess 4 => Serializable 5 => RecursiveIterator 6 => OuterIterator 7 => SeekableIterator 8 => Countable 9 => SplObserver 10 => SplSubject 11 => Reflector 12 => fax 13 => printer From the list above you can see the SPL interfaces available and at the bottom is our fax and printer interfaces. public function printColor(). printer{ public function dial(){ } public function send(){ } public function recieve(){ } public function printBlack(){ } public function printColor(){ } public function printDraft(){ } public function kick(){ } } /*** create and printerfax object ***/ $object = new printerFax.. public function send().'<br />'.$interface.' =&gt. public function printDraft(). public function kick().

echo 'Declared classes are:<br /> '. This is commonly achieved with the include() or require() functions such as below. } ?> The little snippet above will produce over one hundred available classes.class.' class<br />'. rather it is an implentation of an interface. shortened here for the sake of sanity.$classname. 18 of 24 6/19/2013 4:46 PM .'<br />'. /*** create an instance of the printer class ***/ $bar = new printer. such as these below. echo '$foo is from the ' get_class($foo).org/tutorials/Object-Oriented-Programming-with-PHP.PHP Tutorials Examples Object Oriented Programming with PHP http://www.. <?php /*** include our class definitions ***/ include('classes/vehicle. '.snip --106 -> fax 107 -> printer Autoload Earlier in this tutorial we stated that the class definition must be included in every call to an object. printerfax is not listed as it is not an interface. Note our fax and printer classes at the bottom of the list. echo class_exists("printer").' -&gt.. $foo is from the fax class 1 0 -> stdClass 1 -> Exception ---8<--.php').phpro. Other functions Here we will see three helper functions for our classes get_class() class_exists() get_declared_classes <?php /*** a pretend class ***/ class fax{ public function dial(){ } public function send(){ } public function recieve(){ } } /*** another pretend class ***/ class printer{ public function printBlack(){ } public function printColor(){ } public function printDraft(){ } public function kick(){ } } /*** create an instance of the fax class ***/ $foo = new fax.'<br />'. foreach(get_declared_classes() as $key=>$classname) { echo $key.

. /*** instantiate a new printer class object ***/ $printer = new printer. ?> Now we can load up as many class definitions as we like because they will be autoloaded when we try to use a class that has not been defined. There are some limitations.php'). But what if we needed to somehow store an object for later retrieval. strtolower($class) . /*** instantiate a new vehicle class object ***/ $vehicle = new vehicle.php'). /*** instantiate a new fax class object ***/ $fax = new fax.class. ?> As you can see. eg: a class definition file named fax would have the filename fax. this is quite cumbersome. Serializing Objects We have seen a lot of code above for the use of objects and how they can save us time (and $$$) by re-using them. Lets see how it performs with a little code.class. } /*** instantiate a new vehicle class object ***/ $vehicle = new vehicle. This can save much coding and much searching for code. It is important to remember the naming convention of your classes and class files. *** instantiate a new fax class object ***/ $fax = new fax.PHP Tutorials Examples Object Oriented Programming with PHP http://www.phpro. /*** instantiate a new motorcycle class object ***/ $bike = new motorcycle. include('classes/printer. *** instantiate a new motorcycle class object ***/ $bike = new motorcycle. '. The __autoload() function will internally search out the class and load its definition. So the above block of code could be reduced to this. perhaps in a database or in a session variable? PHP has given us the serialize() function to make this rather effortless.. but this can be a very useful tool for applications. include('classes/printer. <?php /*** Autoload class files ***/ function __autoload($class){ require('classes/' . The solution to this sort of mess is __autoload().class.php'). include('classes/motorcycle. Each class file should be named the same as the class definition itself. <?php 19 of 24 6/19/2013 4:46 PM . *** instantiate a new printer class object ***/ $printer = new printer.php The use of the strtolower() function assures compatibility of naming conventions as windows machines fail to be case sensitive for filenames.php').org/tutorials/Object-Oriented-Programming-with-PHP.class.class.

} } /*** end of class ***/ /*** create a new class object ***/ $obj = new my_class. } /*** __call() method with two args ***/ public function __call($method.. Lets put it to the test with two args. The __call() method takes two arguements. $arg){ echo $method.phpro. PHP will try to create the function and you have any code within the _call() method that you like. "arg2"). ?> The above code will print the following bar Array ( [0] => arg1 [1] => arg2 ) 20 of 24 6/19/2013 4:46 PM . and the arguements.PHP Tutorials Examples Object Oriented Programming with PHP http://www. /*** code here ***/ ?> Overloading Comes a time in every programmers life when.hmm Overloading in PHP has caused much confusion for no real reason.'<br />'. <?php class my_class{ public function foo() { return "This is the foo function". } } /*** end of class ***/ /*** create a new class object ***/ $obj = new my_class. This special function is only called when the original method name does not exist.. With the __call() function in place. /*** call a non-existant method ***/ $obj->bar("arg1". Enter __call()..php on line 12 because we have called the bar() class method that does not exist. the method name. ?> Of course the above snippet of code will produce an error such as Fatal error: Call to undefined method my_class::bar() in /www/overload. Method Overloading is achieved by a special function named __call(). <?php class my_class{ public function foo() { return "This is the foo function". print_r($arg). It is available as a sort of method wildcard for calls to undefined methods within a class.. Your call to the undefined method may have many arguements and these are returned in an array. The __call() will only work when the class method you are trying to access does not exist. PHP Overloading can be broken downinto two basic components Method overloading Property overloading Simply put.org/tutorials/Object-Oriented-Programming-with-PHP. /*** call a non-existant method ***/ $obj->bar(). Lets take it for a spin..

'<br />'. and __set() is called when trying to change that properties value. echo 'Item: ' . $obj->getItem() . } } } $obj = new readyGetSet. 0. The __get() function is called when reading the value of an undefined property. Lets see how it works by example. The __call() method has returned the method name that we called along with the array of args passed to it. $obj->getPrice() . echo 'Price: ' . $arguments){ /*** set property and prefix ***/ $prefix = strtolower(substr($method. '<br />'.phpro. '<br />'. '<br />'. } if ($prefix == 'get' && isset($this->$property)) { return $this->$property. /*** our call function ***/ function __call($method. /*** declare the price ***/ private $price = 100.. ?> The second part of overloading refers to properties and the ability to be able to dynamically get and set object properties. $obj->setPrice(25). Lets now look at we can dynimically manipulate or overload our data. 3)).PHP Tutorials Examples Object Oriented Programming with PHP http://www. if (empty($prefix) || empty($property)) { return. $obj->setItem('CD'). } if ($prefix == 'set') { $this->$property = $arguments[0]. <?php class candy{ /*** declare a property ***/ public $type='chocolate'. echo 'Price: ' .. /*** a normal method ***/ public function wrap(){ 21 of 24 6/19/2013 4:46 PM . I hope this is clear as it can get a little confusing. $obj->getPrice() . $obj->getItem() . echo 'Item: ' . <?php class readyGetSet { /*** declare $item ***/ private $item = 'Skate Board'.org/tutorials/Object-Oriented-Programming-with-PHP. 3))... $property = strtolower(substr($method.

'<br />'. } /*** our __set() function ***/ public function __get($index){ echo 'Retrieving element of $choctype property with index of '. 'dark'=>1. We then see in our __set method that it echoes the name of the variable. } } /*** end of class ***/ /*** a new candy object ***/ $candy = new candy. the name of the non existant variable.$candy->milk. /*** set a non existant property ***/ echo 'The value of the following element property is '. It has a simple method and our __set() method.' is '. /*** a normal method ***/ public function wrap(){ echo 'Its a wrap'. public $choctype = array('milk'=>0. ?> The result from above will be: The value of bar is Blue Smarties Lets see what we have done.. After the class our user code creates a new instance of the candy class. plus its intended value. /*** set a non existant property ***/ $candy->bar = 'Blue Smarties'.$value. Here the __set method takes control and assigns it for us. ?> From the above code we get the result Retrieving element of $choctype property with index of milk The value of the following element property is 0 Class Constants 22 of 24 6/19/2013 4:46 PM . } } /*** end of class ***/ /*** a new candy object ***/ $candy = new candy..$index. and its intended value. echo 'Its a wrap'. $value){ echo 'The value of '. We have described a class named candy which contains a public property named $type. return $this->choctype[$index]..$index.. } /*** our __set() function ***/ public function __set($index. The __set() method takes two arguements.. The __get() method .phpro. Then we try to set a variable that does not exist in the class.PHP Tutorials Examples Object Oriented Programming with PHP http://www. 'plain'=>2). <?php class candy{ /*** declare a property ***/ public $type='chocolate'.org/tutorials/Object-Oriented-Programming-with-PHP.

public function show(){ echo self::_ERROR_MSG. /*** echo the constant ***/ echo _ERROR_MSG.PHP Tutorials Examples Object Oriented Programming with PHP http://www. but example is always clear. It cannot be a variable or the result of a function or method. 'An Error has occured!'). I'd rather have you walk with me. To define a standard constant we use this code: /*** define an error message ***/ define('_ERROR_MSG'. I would rather see a sermon than hear one any day. You have more than likely seen the use standard constants in PHP. If you have anything you would like to see here just contact us and we will do our best to help. /*** static call to the show method() ***/ my_class::show(). Banga Sanga 23 of 24 6/19/2013 4:46 PM . <?php class my_class { /*** define a class constant ***/ const _ERROR_MSG = 'An Error has occured!'. } } /*** end of class ***/ ?> There are now three ways the class constant can be access from this example. a constant value. /*** instantiate a class object ***/ $my_class = new my_class. ?> Each of the above methods would output the same line An Error has occured! A class constant. Home PHPRO. <?php /*** static call to constant ***/ echo my_class::_ERROR_MSG. /*** can run the show() method ***/ $my_class->show().ORG.ORG Tutorials Articles Examples Tutorials Articles Examples Classes Contact Us Copyright 2008 PHPRO. than merely point the way. ?> The above snippit would output An Error has occured! To define a class constant we use the const keyword.phpro. must be exactly as the name suggests. All Rights Reserved.org/tutorials/Object-Oriented-Programming-with-PHP.. good advice is often confusing. The eye is a more ready pupil than ever was the ear. Credits This concludes our little insight into PHP OOP.. like standard constants.

org/tutorials/Object-Oriented-Programming-with-PHP. 24 of 24 6/19/2013 4:46 PM .PHP Tutorials Examples Object Oriented Programming with PHP http://www.phpro...

Sign up to vote on this title
UsefulNot useful