从对象内部访问同级对象

时间:2011-06-22 13:48:17

标签: php oop

我在标题中制定问题时遇到了一些问题,但我希望你能给我一些示例代码。

基本上:

在面向对象的项目中,我想访问“父”对象中定义的对象。 考虑这个片段:

class Bar
{
    public $var;
    public function Bar()
    {
        $this->var = 'value';
    }
}

class Bogus
{
    public function Bogus()
    {
        //Here i want to access the methods and vars of obj1 in the "parent" object
    }
}
class Foo
{
    public $obj1,$obj2;

    function Foo()
    {
        $this->obj1 = new Bar();
        $this->obj2 = new Bogus();
    }
}

正如你所看到的那样,“child”对象并不是真正的孩子,因为它们扩展了“父”类,而只是对象内部实例化的对象。

有没有“哦该死的很酷”有点这样做或者我必须将物品传递给彼此 喜欢:

$this->obj2 = new Bogus($this->obj1);

或利用全局对象,实现类外的对象:

global $bar,$bogus;
class Foo
{
    public $obj1,$obj2;

    function Foo()
    {
        global $bar,$bogus;
        $this->obj1 = $bar   = new Bar();
        $this->obj2 = $bogus = new Bogus();
    }
}

我希望你能理解我的目标;)

3 个答案:

答案 0 :(得分:1)

我会将父对象提供给子对象,也许不是通过构造函数,而是使用setter。如果设置了父级,那么我们就可以访问其子级:

/* in Bogus ... */

public function setParent($parent)
{
    $this->parent = $parent;
}

public function getSiblingVar()
{
    if (!empty($this->parent->obj1))
    {
        return $this->parent->obj1->var;
    }
    return false;
}

/* in Foo ... */

$this->obj1 = new Bar();
$this->obj2 = new Bogus();
$this->obj2->setParent($this);

我还会为对象使用一些子对象变量,然后你可以迭代一个对象兄弟,引用它们的父对象。

public function getSiblingVar($sibling_id,$var_name)
{
    if (!empty($this->parent->children[$sibling_id]))
    {
        return $this->parent->children[$sibling_id]->getVar($var_name);
    }
    return false;
}

答案 1 :(得分:1)

我想您可能想要使用Singleton PatternCreating the Singleton design pattern in PHP5)。

虽然您可能也希望对design patterns进行更多一些研究,但具体来说您可能需要查看Is there a use-case for singletons with database access in PHP?

答案 2 :(得分:0)

这些对象是相同的类型,相同的类还是组成更大对象的不同对象?

  1. 相同类型,示例嵌套文件夹和O.S。

  2. 中的文件
  3. 不同的类型,组成一个更大的项目,如由车轮,电机等组成的类车。