1

在此示例中,如何从 object$containerObj中的getContainerID()方法访问 object 中的属性$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();
4

1 回答 1

5

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

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

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

你最好改变你的方法,让容器知道分配给它的对象(反之亦然):

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();
于 2012-05-22T14:49:03.613 回答