-->

How to access parent's class property if the c

2019-09-09 15:21发布

问题:

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).