Constructors and Destructors
If you think back to the example where each dog had a DogTag
object in it, this led to code like the following:
$poppy = new Poodle; $poppy->Name = "Poppy"; $poppy->DogTag = new DogTag; $poppy->DogTag->Words = "If you find me, call 555-1234";
Using that method, if we had other objects inside each Poodle
object, we would need to create the Poodle plus all its other associated objects by hand.
Another way to do this is to use constructors . A constructor is a special method you add to classes that is called by PHP whenever you create an instance of the class. For example:
class DogTag { public $Words; } class Dog { public $Name; public $DogTag; public function bark() { print "Woof!\n"; } public function _ _construct($DogName) { print "Creating a Dog: $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";
Note the _ _construct()
method 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 other important things to note:
The constructor is not in the
Poodle
class, it's in theDog
class. When PHP looks for a constructor inPoodle
, and fails to find one there, it goes to its parent class (wherePoodle
inherited from). If it ...
Get PHP in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.