8.3. 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 property $poppy. Poppy, being a Dog, can bark by using the bark( ) method, and to do this, you need to use the special -> operator. Here is a complete script demonstrating creating objectsnote that the method override for bark( ) is commented out.
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( ) method in the Poodle class; running it again, you should see "Yip!" instead.
|