2013-03-27 15 views
0

我有下面這段代碼的問題: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

我不知道爲什麼,這是行不通的! !如果任何人可以擺脫任何光線,這將不勝感激。

感謝

回答

2

好了,你沒有一個名爲 「settings['paths']['protocol']」 屬性。你有一個名爲settings的房產,其中有鑰匙paths,鑰匙。但是PHP不會像複製和粘貼代碼那樣解釋$this->{$string},它會查找名爲「settings['paths']['protocol']」的屬性,該屬性不存在。這對於OOP代碼來說並不是什麼特別的東西,它是任何變量變量的工作原理。


我建議這樣的事情,而不是:

/** 
* Get settings, optionally filtered by path. 
* 
* @param string $path A path to a nested setting to be returned directly. 
* @return mixed The requested setting, or all settings if $path is null, 
*    or null if the path doesn't exist. 
*/ 
public function get($path = null) { 
    $value = $this->settings; 

    foreach (array_filter(explode('.', $path)) as $key) { 
     if (!is_array($value) || !isset($value[$key])) { 
      return null; 
     } 
     $value = $value[$key]; 
    } 

    return $value; 
} 

這樣調用:

$obj->get('paths.protocol'); 

而只是爲了好玩,這裏的功能實現上述的: ; -3

public function get($path = null) { 
    return array_reduce(
     array_filter(explode('.', $path)), 
     function ($value, $key) { return is_array($value) && isset($value[$key]) ? $value[$key] : null; }, 
     $this->settings 
    ); 
} 
+0

你知道這類問題的解決方法嗎?感謝您的解釋,我現在明白了這個問題! – 2013-03-27 13:17:14

+0

你想要做什麼?示例代碼很難講,因爲你不會像那樣真正使用它,我想。 – deceze 2013-03-27 13:18:06

+0

好吧,看更新。 – deceze 2013-03-27 13:21:24