php tutorials examples object oriented programming with php

Upload: muki-singh

Post on 03-Apr-2018

244 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    1/24

    Login or Register Now Email: Password:

    Home Tutorials Articles Examples Projects Classes Manual Contact

    Object Oriented Programming with PHP

    by Kevin Waterson

    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()

    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 ObjectSimply 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

    Suppor t PHPRO.ORG

    Search

    Web www.phpro.org

    PHPRO.ORG Poll

    When programming, do youprefer:

    Caffeine

    Weed

    Alcohol

    Barbituates

    Opiates

    All of the above

    Warning: Participation in PHP RO.ORG polls

    may incorrectly lead you to believe your

    opinions matter.

    RSS Feed

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

    4 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    2/24

    the object.

    What is a ClassA 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.

    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.

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    3/24

    / *** cr eate a new vehi cl e obj ect ** */

    $vehi cl e = new vehi cl e ;

    / *** t he brand of vehi cl e ***/

    $vehi cl e - >br and = ' Por sche' ;

    / *** t he shape of vehi cl e ***/

    $vehi cl e - >shape = ' Coupe' ;

    / *** t he col or of t he vehi cl e ***/

    $vehi cl e - >col or = ' Red' ;

    / ** * number of doors ** */

    $vehi cl e - >num_door s = 2;

    / *** cost of t he vehi cl e ***/

    $vehi cl e - >pr i ce = 100000 ;

    / *** cal l t he showPri ce method ***/

    $vehi cl e - >showPr i ce ( ) ;

    / ** * cal l t he numDoor s met hod *** /

    $vehi cl e - >numDoor s ( ) ;

    / *** dri ve t he vehi cl e ***/

    $vehi cl e - >dr i ve ( ) ;

    ?>

    Using the combination of the two code boxes above, you should have something like..

    About this vehicle.

    This vehicle costs 100000.

    This vehicle has 2 doors.

    Lets step through the class definition first to see what its all about.

    We began the class with the class keyword. This tells PHP that what follows is a class definition.

    Next we declared some variables, or as they are known in the OOP world, properties .

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    4/24

    ?>

    The properties are the individual charactaristics of the vehicle object. The public declares that this property may be

    accessed within the public scope. This means you may set it from within your code. Next in the class definition is this

    code..

    The constructor method (function) is a special function that is executed every time a new object is created or

    "instantiated". If a class needs to do something before running some code, then this is the place to do it. It is often used

    to set properties within the class. You may pass a variable directly to the constructor from your code, but more of that

    later. Following the constructor is several methods (functions) that do things. These methods are also preceded by thepublic meaning they are available with the scope of your code.

    As you see above, our methods are similar to normal PHP functions. However you may note the use of variables like

    $this->price and $this->num_doors. The keyword $this is used to refer to properties or methods within the class itself.

    The $this keyword is reserved in PHP, so it cannot be used as a variable or property name. Finally we finished our class

    definition with a closing }. I like to put a comment beside it so I dont delete it or get it confused with a function I am

    writing.

    Following on from the class definition we see our userland code. This is the code we use to instantiate (create) a new

    instance, or new object, of our vehicle class. As mentioned earlier we do this with the use of the new keyword.

    The code above creates a new object from our class definition called $vehicle . It is at this time that the constructor is

    called and any code within the constructor is executed. Once we have a new object we can then begin to assign values

    to the properties of that object as seen here.

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    5/24

    / *** t he brand of vehi cl e ***/

    $vehi cl e - >br and = ' Por sche' ;

    / *** t he shape of vehi cl e ***/

    $vehi cl e - >shape = ' Coupe' ;

    / *** t he col or of t he vehi cl e ***/

    $vehi cl e - >col or = ' Red' ;

    / ** * number of doors ** */

    $vehi cl e - >num_door s = 2;

    ?>

    With the properties set as above, it is now simple to use the object methods to manipulate the object by calling the

    methods. The methods are executed like this below.

    So, thats the step-by-step of your first class. You see how easy it would be now to create a new car object. Perhaps a

    Red Ferrari with 4 doors costing $250,000.00.

    Commenting CodeIn the previous sections you have seen comments for almost every line of code. This is a good practice, although some

    may find it excessive, as it may not be you who has to edit the code next time. OOP can get very abstracted and if you

    are not careful it is easy to lose site of your programmatical work flow. Most methods within a class will return a value,

    rather than echo a line of HTML code. A class method may also take one, or several, arguements. It is good practice to

    show what these arguements are and there types. An example follows below.

    The above function is rather simplistic, but shows well the commenting of code. The comments begin in a block of C

    type multiline comments and gives us a brief description of what it does, followed by the parameter it takes, in this case

    an array of numbers. It tells us that access to the function is private (more on this in the next section). Finally the

    comment block tells us that the return value is of type INT. We can also see within the function itself a single line

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

    4 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    6/24

    comment just to show what is happening within the funtion itself. If you follow these practices you code will always be

    readable and easy to follow by yourself and others.

    Inheritance (Extending a class)Probably the greatest feature of the PHP OOP model is Inheritence. Inheritence is the ability of php to extend classes

    (child classes) that inherit the charactaristics of the parent class. The resulting object of an extend class has all the

    charactaristics of the parent class, plus whatever is in the new child, or extended class. In this instance we will extend

    the vehicle class and add a motorcyle. A motorcycle is still a vehicle and shares many of the same attributes such as

    price, drive etc. But a motorcycle has some unique features that a car does not.

    Rather than type out the whole of the vehicle class definition again, we will save it in a file of its own called

    vehicle.class.php. It is important here to note the naming convention here as it will be important later in this tutorial. Lets

    see how it works.

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    7/24

    * Show t he numbers of si decar s

    *

    * @r eturn str i ng

    *

    ** /

    publ i c f uncti on showSi deCar ( ) {

    echo ' Thi s motorcyl e has ' . $t hi s - >numSi decars . ' si decar
    ' ;

    }

    } / *** end of cl ass ***/

    / *** our user l and code ***/

    / *** cr eate a new vehi cl e obj ect ** */

    $vehi cl e = new motor cycl e ;

    / *** t he brand of vehi cl e ***/

    $vehi cl e - >br and = ' Harl ey Davi dson' ;

    / *** t he shape of vehi cl e ***/

    $vehi cl e - >shape = ' Spor t s t e r ' ;

    / *** t he col or of t he vehi cl e ***/$vehi cl e - >col or = ' Bl ack' ;

    / ** * number of doors ** */

    $vehi cl e - >num_door s = 0;

    / *** cost of t he vehi cl e ***/

    $vehi cl e - >pr i ce = 25000 ;

    / *** t ype of handl e bars *** /

    $vehi cl e - >set Handl ebars ( ' Ape Hanger s' ) ;

    / *** set t he si decar ***/

    $vehi cl e - >setSi decar ( 1 ) ;

    / ** * show t he vehi cl e br and and t ype ***/

    echo $vehi cl e - >brand . ' : ' . $vehi cl e - >shape . '
    ' ;

    / *** cal l t he showPri ce method ***/

    $vehi cl e - >showPr i ce ( ) ;

    / *** show t he si decar s ** */

    $vehi cl e - >showSi deCar ( ) ;

    / *** dri ve t he vehi cl e ***/

    $vehi cl e - >dr i ve ( ) ;

    ?>

    You see in the motorcycle class that we have used the keyword extends to extend our vehicle class. We can then

    proceed to set vars in the both the parent class and the child class. The child class has inherited all the characaristics of

    the parent vehicle class.

    If you run the above code with out including the parent class, you will get a Fatal Error like this:

    Fatal error: Class 'vehicle' not found in /www/oop.php on line 3

    You MUST include th e class definition on *every page* when you store an object

    This means when you use an object or wish to extend from it. you must include the class file. Either as code, or most

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

    4 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    8/24

    commonly, with an include() statement.

    Visibility (public, private, protected) The visibility of class members, (properties, methods), relates to how that member may be manipulated within, or from

    outside the class. Three levels of visibilty exist for class members.

    public

    private

    protected

    By default, all class members are public. This means if you do not declare a property or method within the class, it will bepublic. It is good practice to declare the visibility of class members for the sake of readability for yourself and others. It is

    much easier for another programmer to see your intentions. This will also future proof your scripts should access

    modifiers be deprecated.

    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. Lets create a simple new class to demonstrate.

    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. Having our properties (variables) visible, or accessible from any

    part of our script works in our favour here, but it can also work against us. A could arise if we lost track of our values and

    changed the value of $num. To counter this problem we can create a method to set the value for us. Even with this in

    place it is still possible for somebody to simply access the $num variable. So we make the variable private. This ensures

    us that the property is only available within the class itself. It is private to the calling class. Consider the following code.

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    9/24

    cl ass mat hemat i cs {

    / ** * a number ** */

    pr i vate $num ;

    / **

    *

    * Set t he val ue of $num

    *

    * @access publ i c

    *

    * @par am $numThe number t o set

    *

    * @r etur n i nt

    *

    ** /

    publ i c f uncti on set Num ( $num ) {

    $th i s - >num = $num ;

    }

    / **

    *

    * Add t wo t o a number*

    * @access publ i c

    *

    * @r etur n i nt

    *

    ** /

    publ i c f uncti on addTwo ( ) {

    return $th i s - >num+2;

    }

    }/ *** end of cl ass ***/

    / *** I nst ant i at e a new cl ass i nst ance ***/$mat h = new mat hemat i cs ;

    / ** * set t he val ue of t he number ** */

    $mat h - >set Num ( 2) ;

    / ** * cal l t he addTwo method ***/

    echo $mat h - >addTwo ( ) ;

    ?>

    ?>

    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.class.php on line 43

    Even if you were to try to access the private $num property from a child class it would fail. This is because private

    methods and properties in a parent class are not visible to child classes and cannot be accessed. To access a parent

    method or property from a child class you need to use the protected keyword. Like the private keyword, protetected

    methods and properties are available only to the class that created them. But unlike private, protected methods and

    properties are visible from a parent class. Lets see how this works.

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    10/24

    pr otected $num ;

    / **

    *

    * Set t he val ue of $num

    *

    * @access publ i c

    *

    * @par am $numThe number t o set

    *

    * @r etur n i nt

    *

    ** /

    publ i c f uncti on set Num ( $num ) {

    $th i s - >num = $num ;

    }

    / **

    *

    * Add t wo t o a number

    *

    * @access publ i c

    *

    * @r etur n i nt*

    ** /

    publ i c f uncti on addTwo ( ) {

    return $th i s - >num+2;

    }

    }/ *** end of cl ass ***/

    cl ass di vi de ext ends mat hemat i cs {

    / **

    *

    * Di vi de a number by t wo*

    * @access publ i c

    *

    * @r etur n i nt

    *

    ** /

    publ i c f uncti on di vi deByTwo ( ) {

    / *** di vi de number by two ***/

    $new_num = $t hi s - >num/ 2 ;

    / *** r et urn t he new number and round to 2 deci mal pl aces ** */

    return r ound ( $new_num , 2) ;

    }

    } / *** end of cl ass ***/

    / *** I nst ant i at e a new cl ass i nst ance ***/

    $mat h = new di vi de ;

    / ** * set t he val ue of t he number ** */

    $mat h - >set Num ( 14 ) ;

    echo $mat h - >di vi deByTwo ( ) ;

    ?>

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

    24 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    11/24

    We can see here the the user space code has called the setNum() method in the parent mathematics class. This

    method, in turn, sets the $num property. We are able to do this because the $num property has been declared protected

    and is visible to the child class.

    FinalAs we saw in the previous section there are ways to protect your code from being used in an improper manner. Another

    way of protecting yourself is the Final keyword. Any method or class that is declared as Final cannot be overridden or

    inherited by another class. Lets put it to the test.

    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.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.

    Abstract ClassesAn abstract class is a class that cannot be instantiated on its own. You cannot create a new object from it. To see this

    lets make a basic class.

    Using the code above, you will get an error something like this

    Fatal error: Cannot instantiate abstract class mathematics in /www/abstract.php on line 23.

    As you can see, this is not allowed. Also if you declare any class method to be abstract, you must also declare the class

    itself as abstract too. So, whats the point you ask? Well, you can inherit from an abstract class. Any class that extends

    an abstract parent class must create an interface of the parent abstract methods. If this is not done a fatal error is

    generated. This ensures that the implementation is correct.

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

    24 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    12/24

    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. The static declaratin must come after the visibility declaration, eg:

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

    24 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    13/24

    public static myClass{

    Because there is no object created when using a static call, the keyword $this and the arrow operator, -> are not

    available. Static variables belong to the class itself and not to any object of that class. To access withing the class itself

    you need to use the self keyword along with the :: scope resolution operator. Lets whip up a quick example of using

    static.

    The above snippet will echo

    Bar

    This is rather basic as an example, so lets use something practical. Static properties are often used as counters. Here

    we will use a basic counter class.

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    14/24

    / *** and a t hi r d i nst ance ***/

    $t hi rd = new count er ;

    echo count er : : get Count ( ) . '
    ' ;

    ?>

    Hopefully by the end of the above snippet you can see what is happening. At each new instance the counter class we

    increment by one. Not also the use of the :: scope resolution operator and self keyword to refer to the static variable

    within the class itself.

    InterfacesInterfaces in PHP allow you to define a common structure for your classes. An interface cannot be instantiated on its

    own. One of the goals of OOP is re-use of code. Interfaces make this a much easier process. The interface methods

    have no internal logic, they are simply a "mapping" or constraint of what the class, or classes, should implement. Here

    we will demonstrate how this works using our vehicle class from earlier, with the addition of a stop() function.

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    15/24

    ** /

    publ i c f uncti on stop ( ) {

    echo ' SSSCCRRREEEEEECCHH! ! !
    ' ;

    }

    } / *** end of cl ass ***/

    / *** decl are our i nterf ace ***/

    i nte r f ace tes tdr i ve {

    / ** * some f unct i ons t hat must be i mpl ement ed ** */

    f uncti on dr i ve ( ) ;

    f uncti on stop ( ) ;

    }

    / *** an new vehi cl e obj ect * **/

    $obj ect = new vehi cl e ;

    / ** * cal l some methods ** */

    $obj ect - >dr i ve ( ) ;

    $obj ect - >stop ( ) ;

    ?>

    You may of course create multiple classes to implement your interface, but they will not inherit from each other. When

    you inherit from a parent class, you may choose to override some of parent methods. If you had multiple parent classmethods with the same name, but different functionality or charactaristics, P HP would have no way of telling which of

    these methods to use. This is why multiple inheritance does not work in PHP. In contrast, classes that implement an

    interface, must implement every method so there is no ambiguity.

    In the real world interfaces provide us with the tools harness parts of multiple classes. Consider this scenario. If we had

    two classes, one for a fax and the other for a printer. Each has seperate uses and could be described like this:

    Both of the above classes give the required usage for each item, but they do not take into consideration the existance of

    a printer/fax machine. To get the usage of both classes we would do something like this:

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    16/24

    publ i c f uncti on k i ck ( ) ;

    }

    cl ass pr i nt erFax ext ends f ax {

    }

    $obj ect = new pri nt er Fax ;

    ?>

    This code works by creating a stack of classes. The grandparent class is fax. Then the printer class extends the fax

    class and inherits all the methods from that class. This is where some problems may arise. The printer class now has thefunction 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. Lets look at

    the design.

    Before we go further, it is recommended you run the above code. It will produce no output but we need to be sure all is

    well. Having run the code, remove the line

    public function kick(){}

    and run it again. 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.php on line 22

    With the kick() function removed from our implementation, we have essentially broken the contract that says we will

    implement every function (method) specified in the interface. We can gather these functions fractionally from multiple

    classes, but we MUST have them all or we will get errors such as the one above.

    Interfaces play a major role in with SPL and it is recommend you implement the interfaces from SPL and not just the

    class methods.

    PHP Class functionsPHP has available several class functions to help you through the OOP mine field.

    get_declared_interfaces()

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

    24 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    17/24

    class_exists()

    get_class()

    get_declared_classes()

    Each of these is shown here beginning with the get_declared_interfaces().

    get_declared_interfaces() This helper function provides an array of all the available declared interfaces.

    The above code should produce a list such as this:

    0 =>Traversable

    1 =>IteratorAggregate

    2 =>Iterator

    3 =>ArrayAccess4 =>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. The

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

    24 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    18/24

    printerfax is not listed as it is not an interface, rather it is an implentation of an interface.

    Other functionsHere we will see three helper functions for our classes

    get_class()

    class_exists()

    get_declared_classes

    The little snippet above will produce over one hundred available classes, shortened here for the sake of sanity, such as

    these below. Note our fax and printer classes at the bottom of the list.

    $foo is from the fax class

    1

    0 ->stdClass

    1 ->Exception

    ---8fax107 ->printer

    AutoloadEarlier in this tutorial we stated that the class definition must be included in every call to an object. This is commonly

    achieved with the include() or require() functions such as below.

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    19/24

    i ncl ude( ' cl asses/motorcycl e. cl ass. php' ) ;

    i ncl ude( ' cl asses/pri nt er. cl ass .php' ) ;

    i ncl ude( ' cl asses/pri nt er. cl ass .php' ) ;

    / *** i nst ant i at e a new vehi cl e cl ass obj ect * **/

    $vehi cl e = new vehi cl e ;

    ** * i ns tant i ate a new mot orcycl e cl ass obj ect ***/

    $bi ke = new mot orcycl e ;

    ** * i ns tant i ate a new pri nter cl ass obj ect ***/

    $pri nt er = new pri nter ;

    ** * i ns tant i ate a new f ax cl ass obj ect ***/

    $f ax = new f ax ;

    ?>

    As you can see, this is quite cumbersome. The solution to this sort of mess is _ _autoload(). The __autoload() function

    will internally search out the class and load its definition. So the above block of code could be reduced to this.

    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. This can save much coding and much searching for code. It is important to remember the

    naming convention of your classes and class files. Each class file should be named the same as the class definition

    itself. eg: a class definition file named fax would have the filename fax.class.php

    The use of the strtolower() function assures compatibility of naming conventions as windows machines fail to be case

    sensitive for filenames.

    Serializing ObjectsWe have seen a lot of code above for the use of objects and how they can save us time (and $$$) by re-using them. But

    what if we needed to somehow store an object for later retrieval, perhaps in a database or in a session variable? PHP

    has given us the serialize() function to make this rather effortless. There are some limitations, but this can be a very

    useful tool for applications. Lets see how it performs with a little code.

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    20/24

    / *** code here ***/

    ?>

    OverloadingComes a time in every programmers life when...hmm

    Overloading in PHP has caused much confusion for no real reason. PHP Overloading can be broken downinto two basic

    components

    Method overloading

    Property overloading

    Simply put, Method Overloading is achieved by a special function named __call () . It is available as a sort of method

    wildcard for calls to undefined methods within a class. This special function is only called when the original method name

    does not exist. The __call () will only work when the class method you are trying to access does not exist. Lets take it for

    a spin..

    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.php on line 12

    because we have called the bar() class method that does not exist. Enter __call(). With the __call() function in place,

    PHP will try to create the function and you have any code within the _call() method that you like. The __call() method

    takes two arguements, the method name, and the arguements. Your call to the undefined method may have many

    arguements and these are returned in an array. Lets put it to the test with two args.

    The above code will print the following

    bar

    Array ( [0] =>arg1 [1] =>arg2 )

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

    24 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    21/24

    The __call() method has returned the method name that we called along with the array of args passed to it.

    Lets now look at we can dynimically manipulate or overload our data.

    The second part of overloading refers to properties and the ability to be able to dynamically get and set object properties.

    The __get() function is called when reading the value of an undefined property, and __set() is called when trying tochange that properties value. I hope this is clear as it can get a little confusing... Lets see how it works by example.

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    22/24

    echo ' I t s a wrap' ;

    }

    / *** our __set( ) f uncti on ***/

    publ i c functi on __ set ( $i ndex , $val ue ) {

    echo ' The val ue of ' . $i ndex . ' i s ' . $val ue ;

    }

    } / *** end of cl ass ***/

    / *** a new candy obj ect ***/

    $candy = new candy ;

    / *** set a non exi st ant propert y ***/

    $candy - >bar = ' Bl ue Smart i es' ;

    ?>

    The result from above will be:

    The value of bar is Blue Smarties

    Lets see what we have done. We have described a class named candy which contains a public property named $type. It

    has a simple method and our __set() method. After the class our user code creates a new instance of the candy class.

    Then we try to set a variable that does not exist in the class. Here the __set method takes control and assigns it for us.

    We then see in our __set method that it echoes the name of the variable, plus its intended value. The __set() method

    takes two arguements, the name of the non existant variable, and its intended value.

    The __get() method ....

    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

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

    24 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    23/24

    You have more than likely seen the use standard constants in PHP. To define a standard constant we use this code:

    / ** * def i ne an err or message ***/

    def i ne(' _ERROR_MSG' , ' An Er r or has occur ed! ' ) ;

    / *** echo the const ant ***/

    echo _ERROR_MSG;

    ?>

    The above snippit would outputAn Error has occured!

    To define a class constant we use the const keyword.

    There are now three ways the class constant can be access from this example.

    Each of the above methods would output the same line

    An Error has occured!

    A class constant, like standard constants, must be exactly as the name suggests, a constant value. It cannot be a

    variable or the result of a function or method.

    Credits This concludes our little insight into PHP OOP. If you have anything you would like to see here just contact us and we

    will do our best to help.

    Home Tutorials Articles Examples Classes Contact Us

    I would rather see a sermon than hear one any day. I'd rather have you walk with me, than merely point the way. The eye is a more ready pupil than ever was the ear, good

    advice is often confusing, but example is always clear.

    PHPRO.ORG Tutorials Articles Examples

    Copyright 2008 PHPRO.ORG. All Rights Reserved. Banga Sanga

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

    24 6/19/2013 4

  • 7/28/2019 PHP Tutorials Examples Object Oriented Programming With PHP

    24/24

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