如何在PHP中访问容器对象?

IMS*_*ard 1 php containers properties object

在这个例子中,我如何$containerObj从对象中的getContainerID()方法访问对象中的属性$containerObj->bar,或者至少获取指向$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();
Run Code Online (Sandbox Code Playgroud)

Lek*_*eyn 5

你不能这样做.可以将对类的引用分配给多个变量,例如:

$bar = new Bar();
$container = new Foo();
$container->bar = $bar;
$container2 = new Foo();
$container2->bar = $bar;
Run Code Online (Sandbox Code Playgroud)

现在哪个Foo容器应该返回PHP?

您最好更改方法并使容器知道分配给它的对象(反之亦然):

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();
Run Code Online (Sandbox Code Playgroud)