简体   繁体   中英

How can I access a container object in PHP?

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM