2012-05-03 122 views
1

我有一個奇怪的問題,我在父類中設置了值,但無法在擴展父類的子類中訪問這些值。訪問子類中的父屬性值

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; 
      .... 
} 

然後我可以從父訪問配置數據。

+0

什麼是'app'類? –

+0

應用程序類其子類 – Eli

回答

2

在任何初始化之前,您正在訪問這些值。首先你必須設定值。

示例:調用方法是在子類的構造器上設置值的父類。

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. 
    } 
} 
+0

hey starx,一週前第一次嘗試幫助我之後,我重新編寫代碼以使其更加簡化。現在我回到了同樣的問題。我認爲擴展父類會繼承所有的屬性值。 – Eli

+0

@Eli,請參閱更新,我希望它可以幫助:) – Starx

+0

我確定它們只是拼寫錯誤,但範圍解析在更新的'$ config'示例中不正確。 –

1

這是因爲家長的財產受到保護。將其設置爲公開,您可以在子類中訪問它。或者,在父類中創建一個返回配置的方法:

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

+1用於正確提示OP使用公共訪問器。 –

+0

@MikePurcell,$ config被保護,同時破壞創建公共訪問器。 – Starx

+0

不知道你的意思是「破壞」,但你是正確的,孩子類應該仍然可以訪問受保護的$配置,認爲它是私人的某種原因。 –