本文介绍了如果当前类已在父级中实例化,则如何访问父级的类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MVC来制作一个简单的框架.这是我正在做的事的一个例子:

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();

问题是我的var_dump返回NULL,那么Main_Controller为什么不读取该App属性?

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

推荐答案

如果子类定义了构造函数,则不会隐式调用父构造函数.为了运行父构造函数,需要在子构造函数内调用parent :: __ construct().如果子级没有定义构造函数,则可以像常规类方法一样从父类继承它(如果未声明为私有).

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

这篇关于如果当前类已在父级中实例化,则如何访问父级的类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 21:18