从对象中获取父对象 [英] get parent object from within an object

查看:66
本文介绍了从对象中获取父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能吗?

假设有两个相同类型的对象:

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

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

现在这是通过 __set() 完成的.在这一点上,我在 object2 的范围内(这是 object1 的一个属性).如何从 __set 函数访问 object1?

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?

推荐答案

你不能.

object1 不是父级,而是容器.如果您想从 object2 访问 object1 函数,您必须有对 object1 的引用.

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.

使用这种模式:

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

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

这就是你要找的吗?

这篇关于从对象中获取父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆