Objects Within Objects

You can use objects inside other objects in the same way as other variable types. For example, we could define a DogTag class and give each Dog a DogTag object like this:

    class DogTag {
            public $Words;
    }

    class Dog {
            public $Name;
            public $DogTag;

            public function bark() {
                    print "Woof!\n";
            }
    }

    // definition of Poodle...

Accessing objects within objects is as simple as using -> again:

    $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";

The $DogTag property is declared like any other, but needs to be created with new once $poppy has been created.

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.