O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 the Dog class. When PHP looks for a constructor in Poodle, and fails to find one there, it goes to its parent class (where Poodle inherited from). If it ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required