How can I access a container object in PHP?

蓝咒 提交于 2019-12-14 02:33:53

问题


In this example, how can I access a property in object $containerObj from the getContainerID() method in object $containerObj->bar, or at least get a pointer to the $containerObj?

class Foo {
  public $id = 123;
}

class Bar {
  function getContainerID() {
    ... //**From here how can I can access the property in the container class Foo?**
  }
}

$containerObj = new Foo();
$containerObj->bar = new Bar();

echo $containerObj->bar->getContainerID();

回答1:


You cannot do that in this way. A reference to a class can be assigned to multiple variables, for example:

$bar = new Bar();
$container = new Foo();
$container->bar = $bar;
$container2 = new Foo();
$container2->bar = $bar;

Now which Foo container should PHP return?

You'd better change your approach and make the container aware of the object that is assigned to it (and vice versa):

class Foo {
    public $id = 23;
    private $bar;
    public function setBar(Bar $bar) {
        $this->bar = $bar;
        $bar->setContainer($this);
    }
}
class Bar {
    private $container;
    public function setContainer($container) {
        $this->container = $container;
    }
    public function getContainerId() {
        return $this->container->id;
    }
}
$bar = new Bar();
$foo = new Foo();
$foo->setBar($bar);
echo $bar->getContainerId();


来源:https://stackoverflow.com/questions/10704365/how-can-i-access-a-container-object-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!