AntonioCorrenti
AntonioCorrenti

Reputation: 158

Parent Object in php

is there a way to traverse an object to get the parent object data? With "parent object" I don't mean the parent class, but literally object. Here an example, in a javascripty world :-) :

$parent->test = "hello world!";

$parent->child = new B();

It would be great If I could access all the data from parent in the child object:

class B{

//I know this doesn't exists, but it's what I wanted do do
    function B(){
        $this->parent = $this->parent();
        echo $this->parent->test; //it would ouput "hello world"
    }
}

For now my solution is to pass the parent object to the child (as a reference) or to make the parent global. Do you have any better solution?

Thanks!

Upvotes: 12

Views: 13624

Answers (6)

Pere Noel
Pere Noel

Reputation: 9

You can create collections of object children when you create the children. you create it trough the parent this way they cannot reference each other but you can access both parents and children trough the parent and trough the children...

class ChildObject
{
    public $name;
}

class ParentObject
{ 
    public $children = array(); 

    public function new_child($text = 'my name is data')
    {
        $child = new ChildObject;   // create a new child
        $child->name = $text;       // assign the name 
        $this->children[] = $child; // store it as part of this object
        return $child;              // return the new instance of Child
    }

    public function print_everything ()
    {
        foreach($this->children as $child) {
            echo $child->name;
        }
    }
}

$parent = new ParentObject;
$child1 = $parent->new_child();     // this is a ChildObject not a ParentObject
$child2 = $parent->new_child('i am not data');

echo $child1->name;                 // 'my name is data' 
echo $child2->name;                 // 'i am not data'

$child1->name = 'something else';
echo $child1->name;                 // 'something else'

$parent->print_everything();        // 'something else' and 'i am not data'

Therefore if you want to access a parent method or property, you should put that in the parent and not in the child. Remember that the parent is also an "instance" of its own class.

Upvotes: 0

Gordon
Gordon

Reputation: 316969

There is no way to invoke

$parent->test = "hello world!";
$parent->child = new B();

and automatically have a reference to $parent in B.


Generally, there is four ways to structure your classes:

1. Aggregate the parent object via Injection, e.g.

class B
{
     private $parent;

     public function __construct($parent) 
     {
         $this->parent = $parent;
     }

     public function setParent($parent) 
     {
         $this->parent = $parent;
     }

     public function accessParent() 
     {
        $this->parent->someMethodInParent();
     }
}

Use constructor injection when the object has to have a parent when it's created. This is a has-a relationship and it creates a very loose coupling. There is no hardcoded dependencies in B, so you can easily swap out the Parent instance, for instance with a Mock when UnitTesting. Using Dependency Injection will make your code more maintainable.

In your UseCase, you'd pass $parent to B when creating B:

$parent->child = new B($parent);

2. Use Composition

class B
{
     private $parent;

     public function __construct() 
     {
         $this->parent = new Parent;
     }

     public function accessParent() 
     {
        $this->parent->someMethodInParent();
     }
}

This is also a has-a relationship, but couples the Parent class to B. It's also not an existing Parent instance, but a new instance. From the wording I find it somewhat odd to have a parent created by the child. Use this, when dependency is a class that is not considered to exist outside of the root class, but is part of the whole thing it represents.

For your UseCase, there is no way of doing $parent->child = new B(); and know what parent is when using this approach, unless $parent is a Singleton. If so, you could get the Singleton instance, e.g. Parent::getInstance() to achieve what you want, but note that Singletons are not everyone's favorite pattern, e.g. hard to test.

3. Use Inheritance

class B extends Parent 
{
    public function accessParent() 
    {
        $this->someMethodInParent();
    }
}

This way you create an is-a relationship. All public and protected methods and properties from the Parent class, (but not of a specific instance) will be available in B and you can access them via the $this keyword of the B instance.

For your UseCase, this approach is not working, as you don't have to have an instance of Parent at all, but B would encapsulate everything of Parent when it's created

$b = new B;

4. Use global keyword

class B extends Parent 
{
    private $parent;

    public function __construct() 
    {
        global $parent;
        $this->parent = $parent;
    }

    public function accessParent() 
    {
        $this->parent->someMethodInParent();
    }
}

The global keyword imports global variables into the current scope. In general, you should avoid using the global keyword in an OO context, but use one of the other three methods above, preferably the first one. While it's a language feature, it's frowned upon - although it is the next closest thing to the first one, e.g.

$parent->child = new B();

Anyway, hope that helps.

Upvotes: 24

Vladimir Fesko
Vladimir Fesko

Reputation: 222

Maybe it can be useful in some case: it doesn't bring parent object to ChildClass very early in constructor, but a one step later. It plays with ability to intercept non-existing method:

class ParentClass
{
    const CHILD_PROPERTY_NAME = 'child';
    public $data = 'Some data';

    public function
    __set($property_name, $property_value)
    {
        if ($property_name == self::CHILD_PROPERTY_NAME)
        {
            $property_value->set_parent_object($this);
        }
    }
}


class ChildClass
{
    private $parent_object = null;

    public function
    set_parent_object($object)
    {
        $this->parent_object = $object;
        echo $this->parent_object->data;
    }

}


$p = new ParentClass();
$p->child = new ChildClass();

This will output Some data

Upvotes: 2

Hinek
Hinek

Reputation: 9729

I'm pretty sure, that PHP does not have something like that.

Your solution of passing the parent-object to the child is the best solution, I think. You should consider to set your Parent-property only in the constructor of the child to prevent multiple parents from having the same child.

Upvotes: 1

Greg K
Greg K

Reputation: 11120

Passing the parent to the child is the better solution. Though it's a somewhat undesirable symbiotic relationship.

Should B() have any knowledge of the object it's an attribute of? More than likely not. These are only loosely related via composition.

Why does B() need to be an attribute of it's parent? Do you need to have this implementation in B() or should it be part of the parent?

Upvotes: 3

Sjoerd
Sjoerd

Reputation: 75588

No.

You can access variables from the superclass using $this:

<?php
class A {
    public function __construct()
    {
        $this->foo = 'hello';
    }
}

class B extends A {
    public function printFoo()
    {
        echo $this->foo;
    }
}

$b = new B();
$b->printFoo();
?>

Upvotes: 0

Related Questions