本文介绍了如何在PHP中访问容器对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中,如何通过 getContainerID()方法访问对象 $ containerObj 中的属性对象 $ containerObj-> bar ,或至少获得指向 $ containerObj 的指针?

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;

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

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

这篇关于如何在PHP中访问容器对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 14:05