PHP三元运算符不解析类属性内部吗? [英] PHP ternary operator doesn't parse inside class property?
问题描述
我试图弄清楚为什么类内部的三元运算符不会解析.我认为,举个例子是最清楚的方法.
I'm trying to figure out why a ternary operator inside of a class will not parse. I think an example is the clearest way to show this.
这很好:
$a = array(
'a' => 'foo',
'b' => 1 ? 'true' : 'false',
'c' => 'baz',
);
print_r($a);
/* Array
(
[a] => foo
[b] => true
[c] => baz
)
*/
但这甚至无法解析:
<?php
class Junk {
private static $a = array(
'a' => 'foo',
'b' => 1 ? 'true' : 'false',
'c' => 'baz',
);
public static function printA() {
print_r(self::$a);
}
}
Junk::printA();
我收到以下消息:
PHP Parse error: syntax error, unexpected '?', expecting ')' in junk.php on line 6
为记录起见,它在数组声明之外也不起作用:
For the record, it doesn't work outside of an array declaration either:
private static $a = 1 ? 'true' : 'false';
给出相同的错误消息.
为什么这行不通?解析引擎中是否只是一些奇怪的错误?我完全困惑. 三元运算符手册指出:运算符是一个表达式,应始终在数组赋值的右侧使用.如果有任何区别,我使用的是PHP 5.4.28.
Why doesn't this work? Is it just some weird bug in the parsing engine? I am completely baffled. The manual on ternary operators states that the operator is an expression, which should always work on the right-hand side of an array assignment. I'm on PHP 5.4.28, if that makes any difference.
推荐答案
类属性必须是常量表达式.
A class property must be a constant expression.
此声明可能包含初始化,但这 初始化必须是一个常数值-也就是说,它必须能够 在编译时进行评估,并且不得依赖于运行时 信息以便进行评估.
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.
http://www.php.net/manual/zh/language.oop5.properties.php
这篇关于PHP三元运算符不解析类属性内部吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!