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

WBOY
Release: 2016-06-20 12:34:59
Original
1617 people have browsed it

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

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

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

但最终运行时报错为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',        );    }}
Copy after login


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


回复讨论(解决方案)

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

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

而系统常量就是确定的值

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

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静态变量不能用其他变量或函数作为值初始化

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!