The Street Way

Objects in PHP

Objects


Classes are mere definitions. You cannot play fetch with the definition of a A. but we can do the next best thing: creating an instance of our class.

In our this example,  We can create 'p' object by using the following syntax:

    $p = new B;

That creates an instance of the class B, and places it into the property $p. B, being a A, can say by using the say( ) method, and to do this, you need to use the special -> operator. Here is a complete script demonstrating creating objects note that the method override for say( ) is commented out.

class A {
            public function say( ) {
                    print "hello!!\n";
            }
    }

    class B extends A {
            /* public function say( ) {
                    print "Yap!\n";
            } */
    }

    $p = new B;
    $p->say( );

 
Execute that script, and you should get "Hello!". Now try taking out the comments around the say( ) method in the B class; running it again, you should see "Yap!" instead.

0 comments:

Post a Comment