用简单的表达式初始化 PHP 类属性声明会产生语法错误 [英] Initializing PHP class property declarations with simple expressions yields syntax error

查看:24
本文介绍了用简单的表达式初始化 PHP 类属性声明会产生语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 PHP 文档,可以在具有以下限制的类中初始化属性:

According to the PHP docs, one can initialize properties in classes with the following restriction:

这个声明可能包括一个初始化,但是这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估,并且不能依赖运行时信息来被评估."

"This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated."

我正在尝试初始化一个数组,但遇到了一些问题.虽然这工作正常:

I'm trying to initialize an array and having some issues. While this works fine:

public $var = array(
    1 => 4,
    2 => 5,
);

这会产生语法错误:

public $var = array(
    1 => 4,
    2 => (4+1),
);

即使这样也不被接受:

public $var = 4+1;

这表明它不是 array() 语言结构的限制.

which suggests it's not a limitation of the array() language construct.

现在,我上次检查时,4+1"等于一个常数值,不仅应该被接受,而且实际上应该被优化掉.无论如何,它肯定可以在编译时进行评估.

Now, the last time I checked, "4+1" equated to a constant value that not only should be accepted, but should in fact be optimized away. In any case, it's certainly able to be evaluated at compile-time.

那么这里发生了什么?与能够在编译时评估"的任何表达式相比,限制真的是根本不能是任​​何计算表达式"吗?文档语言中评估"的使用表明允许简单的计算,但唉......

So what's going on here? Is the limitation really along the lines of "cannot be any calculated expression at all", versus any expression "able to be evaluated at compile time"? The use of "evaluated" in the doc's language suggests that simple calculations are permitted, but alas....

如果这是 PHP 中的错误,是否有人有错误 ID?我试图找到一个,但没有任何运气.

If this is a bug in PHP, does anyone have a bug ID? I tried to find one but didn't have any luck.

推荐答案

PHP 在编译时不做这样的操作;您不能将计算值分配给常量,即使所有运算符本身都是常量.类成员的默认值的处理方式完全相同.我在尝试将 2 的幂分配给常量时遇到了这种行为:

PHP doesn't do such operations at compile-time; you cannot assign calculated values to constants, even if all operators are constants themselves. Default values of class members are treated the exact same way. I encountered this behaviour as I tried to assign powers of two to constants:

class User {
    const IS_ADMIN = 1;
    const IS_MODERATOR1 = 1 << 1; // Won't work
    const IS_MODERATOR2 = 0x02;   // works
}

这篇关于用简单的表达式初始化 PHP 类属性声明会产生语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆