2011-03-25 25 views
0

我想知道爲什麼這不起作用?我設置了一個屬性(數組)和一個值,它必須從類中的一個方法中獲得,我想我正在做的事情,我真的不應該但我會非常感激,爲什麼它不解釋工作以及如何將工作;)如何在PHP中設置屬性時正確調用方法(如果可能的話)

我是新來

Class Widget{ 

    public $settings = array('setting1',array(
    'subsetting1'=> 1, 
    'subsetting2' =>$this->WidgetFunction() 
    )); 

      function WidgetFunction() { 
      echo 'works'; 
      } 
} 

獲得以下錯誤:

Parse error: syntax error, unexpected T_VARIABLE on line 7 
(where WidgetFunction is called) 

回答

8

PHP manual

Class member variables are called "properties". [...] They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

您應該在您的constructor中指定此值。

Class Widget { 

    public $settings; 

    function __construct() { 
    $this->settings = array(
     'setting1' => array(
     'subsetting1' => 1, 
     'subsetting2' => $this->WidgetFunction()) 
    ); 
    } 

    function WidgetFunction() { 
    echo 'works'; 
    } 
} 

(順便說一句,我想你可能是想用「設置1」作爲數組的數組的索引 - 正如我在代碼示例做到了)

+0

太好了,謝謝你這麼多,也用於代碼更正,非常感謝! – JanWillem 2011-03-25 12:58:44

+0

@JanWillem,不客氣! ;) – Czechnology 2011-03-25 13:00:07

相關問題