问题
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