Initialising a static variable in PHP

后端 未结 3 965
野趣味
野趣味 2021-01-22 14:42

Taken from the PHP manual:

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are no

3条回答
  •  轮回少年
    2021-01-22 15:22

    array() is not a function, it's an initializer. Unlike ordinary functions, it's interpreted at compile time, so it can be used to initialize a static.

    For the reference, this is what is allowed after the static keyword:

    static_scalar_value:
        common_scalar  (e.g. 42)
        static_class_name_scalar (Foo::class)
        namespace_name      (Foo)
        T_NAMESPACE T_NS_SEPARATOR namespace_name (namespace \Foo)
        T_NS_SEPARATOR namespace_name (\Foo)
        T_ARRAY '(' static_array_pair_list ')' e.g. array(1,2,3)
        '[' static_array_pair_list ']' e.g. [1,2,3]
        static_class_constant e.g. Foo::bar
        T_CLASS_C (__CLASS__)
    

    http://lxr.php.net/xref/PHP_5_5/Zend/zend_language_parser.y#945

    Php 5.6 adds "static operations" to this list, which makes it possible to use expressions for statics, as long as these ultimately resolve to static scalars.

    class X {
        static $foo = 11 + (22/11); // syntax error in 5.5, valid in 5.6
    }
    

提交回复
热议问题