Alex
Alex

Reputation: 68438

get parent object from within an object

Is this possible?

Let's say there are two objects of the same type:

$object1->object2->property = 'xxxx';

now this is done trough __set(). At this point I'm within object2's scope (which is a property of object1). How can I access object1 from that __set function?

Upvotes: 3

Views: 10119

Answers (2)

Travis
Travis

Reputation: 40

Try using parent:: from within the child class.

Upvotes: 0

zessx
zessx

Reputation: 68790

You can't.

object1 isn't the parent, it's the container. If you want access to an object1 function from object2, you must have a reference to object1.

Use this kind of pattern :

class class1 
{ 
   public $child; 
   public function __construct() 
   { 
      $this->child = new class2($this);
   }
} 

class class2 
{
   private $parent;
   public function __construct(class1 $parent) 
   {
      $this->parent = $parent; 
   }
}

Is that what you're looking for ?

Upvotes: 5

Related Questions