2017-06-05 43 views
0

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->設置中的某些內容被打破。我怎樣才能做到這一點?我有一些設置文件,我需要使用函數從它們中獲取值。我不想在每個設置文件中定義相同的功能。

回答

0

您可以設置private範圍$ A到protected $一個

可以

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

沒有它的時候你會打電話mySettings = $abc->GetValue('a');它會調用BaseSetting::GetValue()BaseSetting背景。由於$aprivate它不會在BaseSetting訪問。要麼您需要將訪問修改器更改爲更低,如publicprotected,或者您需要呼叫覆蓋getValue()並致電返回parent::getValue($setting)

+0

'回報父母::的GetValue($設置)訪問屬性沒有按'如果屬性修飾符保持「私有」,則不起作用。 – paul

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;