Objects

Classes are mere definitions - you cannot play fetch with the definition of a dog, you need a real, live, slobbering dog. Naturally we cannot create live animals in our PHP scripts, but we can do the next best thing - creating an instance of our class.

In our earlier example, "Poppy" was a dog of type "poodle". We can create Poppy by using the following syntax:

$poppy = new poodle;

That creates an instance of the class poodle, and places it into the variable $poppy. Poppy, being a dog, can bark by using the bark() function, and to do this you need to use the special -> dereference marker. Here is a complete script demonstrating creating objects - note that the function override for bark() is commented out.

<?php
    
class dog {
        public function
bark() {
            print
"Woof!\n";
        }
    }

    class
poodle extends dog {
        
/* public function bark() {
            print "Yip!\n";
        } */
    
}

    
$poppy = new poodle;
    
$poppy->bark();
?>

Execute that script, and you should get "Woof!". Now try taking out the comments around the bark() function in the poodle class, and running it again you should see "Yip!" instead.

 

Next chapter: Variables >>

Previous chapter: Overriding functions

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar