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

查看:356
本文介绍了用简单表达式初始化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.

这里发生了什么事?是什么限制真的沿着不能是任何计算表达式,对任何表达式能在编译时评估?在文档的语言中使用评估表明允许进行简单的计算,但是alas ....

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不会在编译时执行这样的操作;您不能将计算值分配给常量,即使所有运算符本身都是常量。类成员的默认值以完全相同的方式处理。我遇到这种行为,因为我试图分配两个常量的权力:

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天全站免登陆