6.10 Constructors and destructorsThis is NOT the latest copy of this book; click here for the latest version.
If you think back to the example where each dog had a dogtag object in it. This led to code like this:
$poppy = new poodle; $poppy->Name = "Poppy"; $poppy->DogTag = new dogtag; $poppy->DogTag->Words = "My name is
Poppy. If you find me, please call 555-1234";
That's pretty clumsy, huh? Imagine how more clumsy it would be if we had other objects inside each poodle object - we would need to create the poodle, plus all its other associated objects!
Luckily, there is a way to avoid this, called constructors. A constructor is a special function you add into your classes that are called by PHP whenever you create an instance of the class. Take a look at this script:
<?php
class dogtag {
public $Words;
}
class dog {
public $Name;
public $DogTag;
public function bark() {
print "Woof!\n";
}
public function __construct($DogName) {
print "Creating $DogName\n";
$this->Name = $DogName;
$this->DogTag = new dogtag;
$this->DogTag->Words = "My name is $DogName. If you find me, please call 555-1234";
}
}
class poodle extends dog {
public function bark() {
print "Yip!\n";
}
}
$poppy = new poodle("Poppy");
print $poppy->DogTag->Words . "\n"; ?>
Yes, that's quite a long script, but it's just a combination of the code we've seen so far, with the new twist that constructors are being used. Note the __construct() function in the dog class, which takes one variable - that is our constructor. Whenever we instantiate a poodle object, PHP calls the relevant constructor.
There are three important things to note:
-
The constructor is not in the poodle class - it is in the dog class. What happens is that PHP looks for a constructor in poodle, and if it fails to find one there, it goes to its parent class (where poodle inherited from), and if it fails to find one there, it goes up again, and up again, ad infinitum, until it reaches the top of the class structure. As the dog class is the top of our class structure, PHP does not have far to go.
-
PHP only ever calls one constructor for you. If you have several constructors in a class structure, PHP will only call the first one it finds.
-
The __construct() function is marked public - that's not by accident. If you don't mark the constructor as public you can only instantiate objects of a class from within the class itself, which is almost an oxymoron. If you make this private, you need to use a static function call - quite messy, but used in some places.
|
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!
|