2011-12-05 12 views
1

可能重複:
Initializing PHP class property declarations with simple expressions yields syntax error是否可以創建一個保存自定義類的實例的關聯數組?

是否有可能建立一個關聯數組和解析的自定義類作爲值的實例?

喜歡的東西:

private static $contentTypeList = array(
    "News" => new ContentType("News", "news.php", "News"), 
    "Termine" => new ContentType("Termine", "termine.php", "Termine"), 
    "Zeitplan" => new ContentType("Zeitplan", "zeitplan.php", "Zeitplan"), 
    "Fotos" => new ContentType("Fotos", "fotos.php", "Fotos"), 
    "Anfahrt" => new ContentType("Anfahrt", "anfahrt.php", "Anfahrt"), 
    "Guestbook" => new ContentType("Guestbook", "guestbook.php", "Gästebuch") 
    ); 

嘗試這個,我得到一個錯誤,如 「意外關鍵字NEW」。

我使用錯誤的語法還是僅僅是不可能?

回答

2

這是可能的,但不是在函數體外聲明屬性時。

它添加到任何功能,例如:

class SomeClass { 
    private static $contentTypeList = array(); 
    public static function init() { 
     self::$contentTypeList = array(
     "News" => new ContentType("News", "news.php", "News"), 
     "Termine" => new ContentType("Termine", "termine.php", "Termine"), 
     "Zeitplan" => new ContentType("Zeitplan", "zeitplan.php", "Zeitplan"), 
     "Fotos" => new ContentType("Fotos", "fotos.php", "Fotos"), 
     "Anfahrt" => new ContentType("Anfahrt", "anfahrt.php", "Anfahrt"), 
     "Guestbook" => new ContentType("Guestbook", "guestbook.php", "Gästebuch") 
    ); 
    } 
} 
+0

它的'private'似乎並不相關。實際上,你的解決方案是次優的:'init'不是'static',你需要兩階段初始化。 –

+0

'變量'有點誤導:它的屬性。 – KingCrunch

+0

@ TomalakGeret'kal:現在應該修復 –

相關問題