How to access parent's class property if the current class has been instantiated in the parent

穿精又带淫゛_ 提交于 2019-12-25 18:41:04

问题


I'm experimenting with MVC trying to make a simple framework. This is an example of what I'm doing:

<?php
require_once('config.php'); //Here I have the Config object
class App{
    protected $config;
    protected $controller;
    public function init(){
        $this->config = new Config;
        $this->controller = new Main_Controller;
    }
}
class Main_Controller extends App{
    public function __construct(){
        var_dump($this->config);
    }
}
$app = new App;
$app->init();

The problem is that my var_dump is returning NULL, so why isn't Main_Controller reading that App property?


回答1:


Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).



来源:https://stackoverflow.com/questions/17958924/how-to-access-parents-class-property-if-the-current-class-has-been-instantiated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!