繁体   English   中英

访问子类中的父属性值

[英]accessing parent property values in child class

我有一个奇怪的问题,我在父类中设置值,但无法访问扩展父类的子类中的值。

class Parent
{
    protected $config;

    public function load($app)
    {
        $this->_config();
        $this->_load($app);
    }

    private function _config()
    {
        $this->config = $config; //this holds the config values
    }

    private function _load($app)
    {
        $app = new $app();
        $this->index;
    }
}

class Child extends Parent
{
    public function index()
    {
        print_r($this->config); // returns an empty array
    }
}

$test = new Parent();
$test->load('app');

当我这样做时,我打印出一个空阵列。 但是,如果我这样做,那么我就能够访问这些配置值。

private function _load($app)
{
    $app = new $app();
    $app->config = $this->config
    $app->index;

}

class Child extends Parent
{
    public $config;
          ....
}

然后我可以从父级访问配置数据。

您在初始化任何内容之前访问这些值。 首先,您必须设置值。

示例:call a method是父类,它在子类的构造函数上设置值。

class Child extends Parent
{
    public function __construct() {
       $this -> setConfig(); //call some parent method to set the config first
    }
    public function index()
    {
        print_r($this->config); // returns an empty array
    }
}

更新:您似乎也对OOP的概念感到困惑

class Parent { ..... }
class child extends Parent { ..... }
$p = new Parent(); // will contain all method and properties of parent class only
$c = new Child(); // will contain all method and properties of child class and parent class

但是,您必须使用父方法和属性,就像在普通对象中一样。

让我们看另一个例子:

class Parent { 
     protected $config = "config";
}
class Child extends Parent {
     public function index() {
           echo $this -> config; // THis will successfully echo "config" from the parent class
     }
}    

但另一个例子

class Parent { 
     protected $config;
}
class Child extends Parent {
     public function index() {
           echo $this -> config; //It call upon the parent's $config, but so far there has been no attempt to set an values on it, so it will give empty output.
     }
}

这是因为父母的财产受到保护。 将其设置为公共,您可以在子类中访问它。 或者,在父类中创建一个返回配置的方法:

public function getConfig()
{
    return $this->config;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM