【问题标题】:Get property from derived class in base class从基类中的派生类获取属性
【发布时间】:2017-11-05 19:11:48
【问题描述】:

base.php:

<?php namespace MyQuestion\Base;

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

派生的.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-> 设置中有问题。我怎样才能做到这一点?我有一些设置文件,我需要使用函数从它们中获取值。我不想在每个设置文件中定义相同的函数。

【问题讨论】:

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


    【解决方案1】:

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

    你可以

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

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

    【讨论】:

    • 如果属性修饰符保留privatereturn parent::GetValue($setting) 不起作用。
    【解决方案2】:

    您只能访问声明属性的类中的私有属性。在你的情况下,它是 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-&gt;a;访问该物业

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2015-03-30
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2010-11-01
      • 1970-01-01
      相关资源
      最近更新 更多