English 中文(简体)
我怎样才能进入PHP的集装箱物件?
原标题:How can I access a container object in PHP?

在此示例中, 我如何访问对象 $containerObj 中的属性? 对象 gang ContainerID () 方法中的属性 $containerObj- gt;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();
问题回答

您不能以这种方式这样做。 对于某一类的引用可以指定给多个变量, 例如 :

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

现在应该归还哪个Foo集装箱?

d 最好改变方向,使容器了解指定的物体(反之亦然):

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




相关问题
Silverlight: Add same UserControl to more than one Canvas

I have a bunch of UserControls ( MyUserControl ) that I want to have a user manually add to one or more Canvases. One instance of a UserControl cannot be a child element of more than one container (...

c++ templated container scanner

here s today s dilemma: suppose I ve class A{ public: virtual void doit() = 0; } then various subclasses of A, all implementing their good doit method. Now suppose I want to write a function ...

Multi-Dimensional Container in Java

I searched around on Google, but I was unable to find any libraries for a multi-dimensional container in Java (preferably one that supports generics as well). I could easily write one (in fact, I ...

c# stack queue combination

is there in C# some already defined generic container which can be used as Stack and as Queue at the same time? I just want to be able to append elements either to the end, or to the front of the ...

Custom container requirement to work with Qt s foreach

What is the bare minimum amount of code to create a custom container that would work with Qt foreach macro? I have this so far template< class T > class MyList { public: class iterator { ...

Having many stacks with different types

I m making a C program that needs to use two stacks. One needs to hold chars, the other needs to hold doubles. I have two structs, node and stack: struct node { double value; struct node *...

热门标签