是否可以创建一个包含自定义类实例的关联数组?

时间:2011-12-05 15:30:04

标签: php

  

可能重复:
  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”。

我使用错误的语法还是不可能?

1 个答案:

答案 0 :(得分: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")
      );
    }
}