数组键作为对象属性

时间:2012-08-29 12:35:39

标签: php oop class static

我有一个PHP类,它有一些静态属性,如:

static public $_TYPE_DESIGN_DRAFT = 'design_draft';
static public $_TYPE_STORYTELLING_DRAFT = 'storytelling_draft';
static public $_TYPE_OTHER = 'other';
static public $_TYPE_DATA_FILE = 'data_file';

static public $_ALLOWED_EXTENSIONS = array(       // on the next line it breaks
                self::$_TYPE_DESIGN_DRAFT => array("jpeg", "jpg", "png", "gif", "pdf", "txt", "rtf", "doc", "csv"),
                self::$_TYPE_STORYTELLING_DRAFT => array("jpeg", "jpg", "png", "gif", "pdf", "txt", "rtf", "doc", "csv"),
                self::$_TYPE_OTHER => array("jpeg", "jpg", "png", "gif", "pdf", "txt", "rtf", "doc", "csv"),
                self::$_TYPE_DATA_FILE => array("pdf", "txt", "rtf", "doc", "csv", "xls")
);

但似乎PHP不允许我使用键的值作为同一类的静态属性来定义类似的数组。

解决方法是仅在类的构造函数中定义$_ALLOWED_EXTENSIONS var,但是我不能使它static,因为在静态时,构造函数不会被调用。< / p>

这是否有一个有效的解决方法?

1 个答案:

答案 0 :(得分:3)

你不能使用这样的类属性。

继续我的评论;你能不做这样的事吗?

class Test
{
    static public $_TYPE_DESIGN_DRAFT = 'design_draft';
    static public $_TYPE_STORYTELLING_DRAFT = 'storytelling_draft';
    static public $_TYPE_OTHER = 'other';
    static public $_TYPE_DATA_FILE = 'data_file';

    static public $_ALLOWED_EXTENSIONS = array();

    public static function init()
    {
        self::$_ALLOWED_EXTENSIONS = array(
            self::$_TYPE_DESIGN_DRAFT => array("jpeg", "jpg", "png", "gif", "pdf", "txt", "rtf", "doc", "csv"),
            self::$_TYPE_STORYTELLING_DRAFT => array("jpeg", "jpg", "png", "gif", "pdf", "txt", "rtf", "doc", "csv"),
            self::$_TYPE_OTHER => array("jpeg", "jpg", "png", "gif", "pdf", "txt", "rtf", "doc", "csv"),
            self::$_TYPE_DATA_FILE => array("pdf", "txt", "rtf", "doc", "csv", "xls")       
        );      
    }
}

Test::init();
print_r(Test::$_ALLOWED_EXTENSIONS);