调用包含另一个对象的对象

时间:2013-11-05 18:24:28

标签: php

所以我希望能够像我想的那样从创建的对象中调用对象的方法。

例如

$test = new sampleObject;
$test2 = $test->createChild();
$test3 = $test2->createChild();
...

catch是,我需要能够从最顶层的创建者类中引用一个方法。

所以我有我的主要课程

class sampleObject
{
    public $tons, $of, $properties;

    public function createChild()
    {
        $someVar = new childObject();
        $this->otherMethod();
        return $someVar();
    }

    public function otherMethod()
    {
        //Do some stuff
    }
}

class childObject
{
    public $child, $properties;

    function createChild()
    {
        $someVar = new childObject();
        //here is my issue
        //I need to call a otherMethod from the creating class here but not static .
        return $someVar;
    }
}

这是错误的方法还是有一种方法可以引用创建类对象的方法。 我想将创建的对象的属性与创建者类保持隔离。

我想过只是传递对象,但是如果可能的话,我想保持相同的结构作为创建者类。

1 个答案:

答案 0 :(得分:0)

我能找到的最好方法是将它所属的对象传递给子对象。

所以$test2 = $test->createChild($test);

class childObject
{
    public $child, $properties, $parent;

    function createChild()
    {
        $someVar = new childObject($parent);
        $this->parent = $parent;
        //here is my issue
        //I need to call a otherMethod from the creating class here but not static .
        return $someVar;
    }
}