6.3 ObjectsThis is NOT the latest copy of this book; click here for the latest version.
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.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|