从基类中的派生类获取属性

时间:2017-06-05 04:31:41

标签: php inheritance properties derived-class base-class

base.php:

<?php namespace MyQuestion\Base;

abstract class BaseSetting
{
    public function GetValue($setting)
    {
        return $this->$setting;
    }
}

derived.php

<?php namespace MyQuestion\Configs;

use MyQuestion\Base;

class Settings extends BaseSetting
{
    private $a = 'value 1';
    private $b = 'value 2';
    private $c = "value 3";
}

的index.php

$abc = new Settings();
$mySettings = $abc->GetValue('a');

我尝试调试代码。在$ this-&gt;设置中有些东西被打破了。我怎样才能做到这一点?我有一些设置文件,我需要使用函数从它们获取值。我不想在每个设置文件中定义相同的功能。

2 个答案:

答案 0 :(得分:0)

您可以将private $ a的范围设置为protected $ a

你可以

class Settings extends BaseSetting
{
 public function GetValue($setting)
    {
        return parent::getValue($setting)
    }
}

如果没有它,当您致电mySettings = $abc->GetValue('a');时,它会在BaseSetting::GetValue()的上下文中调用BaseSetting。由于$aprivate,因此无法访问BaseSetting。要么您需要将访问修饰符更改为publicprotected,要么需要调用覆盖getValue()并从那里调用return parent::getValue($setting)

答案 1 :(得分:0)

您只能访问声明属性的类中的私有属性。在你的情况下,它是Settings的类。

我完全不知道你想要什么,但是可以解决这个问题

class Settings extends BaseSetting
{
    private $a = 'value 1';
    private $b = 'value 2';
    private $c = "value 3";

    public function __get($attr)
    {
        return $this->$attr;
    }
}

然后您可以通过$mySettings = $abc->a;

访问该媒体资源