gpt4 book ai didi

php - 在 PHP 中初始化静态变量

转载 作者:行者123 更新时间:2023-12-04 15:52:28 26 4
gpt4 key购买 nike

取自 PHP manual :

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

所以这意味着我不能执行以下操作,因为 a) 不允许表达式,b) 不允许函数返回值。

class MyClass {
// I can't do this.
public static $var = 10 * 2;

// I can't do this.
public static $sum = array_sum( array( 3, 5, 6 ) );
}

但是,引用b)函数返回值不允许,为什么当array()是一个有返回值的函数时可以执行以下操作?

class MyClass {
// I can do this.
public static $array = array( 3, 5, 6 );
}

最佳答案

array() 不是一个函数,它是一个初始化器。与普通函数不同,它是在编译时解释的,因此可以用于初始化静态函数。

作为引用,这是 static 关键字之后允许的内容:

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 向此列表添加了“静态操作”,这使得可以使用静态表达式,只要这些表达式最终解析为静态标量即可。

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

关于php - 在 PHP 中初始化静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28394109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com