The Street Way

Objects Within Objects in PHP

Objects Within Objects


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

class ATag {
            public $Words;
    }

    class A {
            public $Name;
            public $ATag;

            public function say( ) {
                    print "Hello!\n";
            }
    }

    // Definition of B...


Accessing objects within objects is as simple as using -> again:
    $p = new B;
    $p->Name = "p";
    $p->ATag = new ATag;
    $p->ATag->Words = "My name is P. If you find me, please call  1234";


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

0 comments:

Post a Comment