我有下面這段代碼的問題:PHP OOP問題與動態多維數組
<?php
class testClass
{
public $settings;
public function __construct()
{
$this->settings = array(
'paths' => array(
'protocol' => 'http'
)
);
}
public function getSomething()
{
$string = "settings['paths']['protocol']";
echo $this->{$string}; /***** Line 19 *****/
}
}
$obj = new testClass;
$obj->getSomething(); // Outputs a 'undefined' notice
echo '<br />';
echo $obj->settings['paths']['protocol']; // Outputs http as expected
?>
這是我使用的代碼的一個非常簡單的例子,實際的代碼是比較先進的,但輸出/產生的錯誤是一樣的。
基本上,類構造函數使用settings數組填充屬性。 getSomething()方法將一個數組路徑分配給一個變量,然後嘗試通過echo $this->{$string};
代碼檢索該變量。
當我寫:$obj->getSomething();
我得到以下錯誤:
Notice: Undefined property: testClass::$settings['paths']['protocol'] in /test.php on line 19
如果我寫了下面的代碼echo $obj->settings['paths']['protocol']
我得到預期的http
我不知道爲什麼,這是行不通的! !如果任何人可以擺脫任何光線,這將不勝感激。
感謝
你知道這類問題的解決方法嗎?感謝您的解釋,我現在明白了這個問題! – 2013-03-27 13:17:14
你想要做什麼?示例代碼很難講,因爲你不會像那樣真正使用它,我想。 – deceze 2013-03-27 13:18:06
好吧,看更新。 – deceze 2013-03-27 13:21:24