Maison  >  Article  >  développement back-end  >  为什么数组初始化时,赋值不能是常量?

为什么数组初始化时,赋值不能是常量?

WBOY
WBOYoriginal
2016-06-20 12:34:591713parcourir

刚刚发现的一个很奇怪的现象

下面这个数组我设置为类的属性,其中SYSTEM_LIB为我定义的常量

final class Application {    public static $_lib=array(        'route'         =>  SYSTEM_LIB.'/lib_route.php',        'mysql'         =>  SYSTEM_LIB.'/lib_mysql.php',    );}

但最终运行时报错为Parse error: syntax error, unexpected 

而我将该数组放入方法中时,就能正常创建
final class Application {    public static $_lib=array();    public static function run(){        self::$_lib =array(            'route'         =>  SYSTEM_LIB.'/lib_route.php',            'mysql'         =>  SYSTEM_LIB.'/lib_mysql.php',        );    }}


我分析是因为当数组被设置为类属性时,数组内的值必须在引号内,数组不认识常量


回复讨论(解决方案)

类定义时,属性不能赋予不确定的值

用户常量是在程序运行时定义的
而语法检查是在程序运行前进行的

而系统常量就是确定的值

class T {  var $os = PHP_OS;}$p = new T;echo $p->os;

Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed. 
与PHP的静态变量一样,静态属性只能使用一个字面值或常量来初始化(PHP5.6之前的版本);表达式是不允许的。

In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time. 
PHP5.6以上版本则与常量表达式的规则一样,可以使用一些特定的表达式,只要其能在编译时被计算

所以你的第一种写法在PHP5.6以上版本是可以正常运行的。

印象中static静态变量不能用其他变量或函数作为值初始化

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn