如何在PHP中设置父变量并从子进程访问它?

时间:2014-08-25 16:09:49

标签: php variables

我试图在PHP中切换到OOP编程方式。我遇到了多个孩子和一个单亲班的问题。

在我父母的构造方法中,我包含一个带有include()方法的子类文件,然后创建一个引用子类的变量,如下所示:

class App {
    function __construct() {
        include_once('childClass.php');
        $this->childvar = new childClass;

        include_once('childClass2.php');
        $this->childvar2 = new childClass2;
    }
}

我的孩子课程如下:

class childClass extends App {
    var test = 1;

    function __construct() {

    }
}

class childClass2 extends App {
    function __construct() {
        echo $this->childvar->test;
    }
}

当我尝试从childClass2访问childClass vriable时,我收到错误

  

未定义的属性:childClass2 :: $ test

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

如果您想在App中使用childClass2的构造函数,请务必先调用parent::__construct();

class childClass2 extends App {
    function __construct() {
        parent::__construct();
        echo $this->childvar->test;
    }
}

请记住,因为这会产生无限循环。


通常,在构造函数中看到new调用并不常见。应该传入任何依赖项。顺便说一下,这也涉及无限循环。您当前的设计存在更多问题。

class App {
    function __construct($child1, $child2) {
        $this->child1 = $child1;
        $this->child2 = $child2;
    }
}
class childClass extends App {
    var test = 1;

    function __construct($child1, $child2) {
        parent::__construct($child1, $child2);
    }
}

class childClass2 extends App {
    function __construct($child1, $child2) {
        parent::__construct($child1, $child2);
        echo $this->childvar->test; // error childvar is null
    }
}

$app = new App(new childClass(null, null), new childClass2(null, null));