获取调用子对象的父对象的任何可能性


Any possibility to get hold of parent calling child object?

以下代码:

 class a{
        public function __get($key) {
            if($key == 'obj') {
                if($b->obj == null) { //PSEUDO this is what I intend to do :)
                   $obj = new Obj();                        
                   $b->obj = $obj
                }
                return $obj;
            }
        }
    }
 class b extends a{
        private $obj = null;

        public function __get($key) {
            return parent::__get($key);
        }
    }

因此,我们的想法是根据需要创建对象。但是我不知道是否可以检测调用parent::_get方法的对象的类。我想我要找的是一些像操作员一样的孩子:)。

可能但多余的是,例如,我有一个名为Country的对象,所以我在类User中定义了一个Country对象,而另一个类Location也有Country对象。这两个类都扩展了类a。我可以通过将类a的if块写入每个子类来解决这个问题。但这是我不想做的。因此,在类a中检查哪个类调用了__get函数,并将所需的Country对象直接设置到子类中会更容易。我希望我的问题变得清楚,不要太奇怪,呵呵。尽管我对任何其他解决方案持开放态度。。。谢谢

http://codepad.org/Qnc938Wv

class a{
    public function __get($key) {
        if($key == 'obj') {
            if($this->_obj == null) { //PSEUDO this is what I intend to do :)
               echo "creating ";
               $obj = new StdClass();                        
               $obj->what = get_class($this);
               $this->_obj = $obj;
            }
            return $this->_obj;
        }
    }
}
class location extends a{
    protected $_obj = null;
    public function __get($key) {
        return parent::__get($key);
    }
}
class user extends a{
    protected $_obj = null;
    public function __get($key) {
        return parent::__get($key);
    }
}
$l = new location();
echo $l->obj->what . "'n";
$u = new user();
echo $u->obj->what . "'n";
echo $l->obj->what . "'n";
echo $u->obj->what . "'n";

这导致

creating location
creating user
location
user

如果您想知道__get()方法内部(通过extensions在许多类之间共享)在使用get_called_class时调用的对象的类是什么。