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

时间:2012-05-22 14:43:51

标签: php object properties containers

在此示例中,如何从对象$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();

1 个答案:

答案 0 :(得分:5)

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

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

现在哪个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();