Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/237.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 调用包含另一个对象的对象_Php - Fatal编程技术网

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

Php 调用包含另一个对象的对象,php,Php,所以我希望能够从一个创建的对象中调用一个对象的方法 比如说 $test = new sampleObject; $test2 = $test->createChild(); $test3 = $test2->createChild(); ... 问题是,我需要能够从最顶层的creator类引用一个方法 所以我有我的主课 class sampleObject { public $tons, $of, $properties; public function crea

所以我希望能够从一个创建的对象中调用一个对象的方法

比如说

$test = new sampleObject;
$test2 = $test->createChild();
$test3 = $test2->createChild();
...
问题是,我需要能够从最顶层的creator类引用一个方法

所以我有我的主课

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;
    }
}
这是错误的方法还是有方法引用创建类对象的方法。 我希望将创建对象的属性与creator类隔离


我考虑只传递对象,但如果可能的话,我希望保持与creator类相同的结构

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

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


按照规范,您的childObject不“扩展”任何内容,因此没有父对象。对,这是我的问题。主类创建子类;但是有没有更正确的方法呢?看看工厂模式。看起来这可能是你想要的。我很难理解当前代码的目的。
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;
    }
}