为什么我可以在 php7 中使用字符串文字作为 class?
Why can I use a string literal as a class in php7?
考虑以下代码:
class foo {
static $bar = 'baz';
}
var_dump('foo'::$bar);
它在 PHP5 中抛出一个错误(正如预期的那样):
Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in [...][...] on line 4
但它在 PHP7 中没有问题并输出:
string(3) "baz"
这是故意的还是错误?
目前我在文档中找不到任何内容,但我怀疑这可能是预期的行为。
考虑 PHP 5 中的以下内容且没有错误:
function hello()
{
echo "hi";
}
$hi = 'hello';
$hi();
$hi
是一个字符串,因此他们似乎只是决定添加对临时字符串的支持。
'hello'();
在 PHP7
中有效是有道理的
更新
您可以在 http://php.net/manual/en/functions.variable-functions.php
示例的底部找到对 PHP 7.0.0 的小参考
我认为这是因为他们重写了有关评估的内容。
像下面这样在 PHP5 中是不可能的,但在 PHP 7 中是不可能的:
echo (new X)->toString();
同样适用于
echo ('X')::$bar
见Changes to the handling of indirect variables, properties, and methods
这主要是关于从左到右的评估,但它也会影响总体评估。
可以在 PHP RFC: Uniform Variable Syntax (Status: implemented) - Thanks to 上找到更多信息:
This RFC proposes the introduction of an internally consistent and
complete variable syntax. To achieve this goal the semantics of some
rarely used variable-variable constructions need to be changed.
PHP 多年来一直在努力的大方向是在可变变量、可变函数和可变 classes 的使用方面更加灵活和通用。在PHP5中,当你想使用一个变量class时,你必须将class名称放在一个变量中:
$class = 'foo';
echo $class::$foo;
看起来 PHP7 使它更通用,允许任何表达式,而不是需要变量。例如,你可以这样写:
$c1 = 'f';
$c2 = 'oo';
echo ($c1 . $c2)::$foo;
考虑以下代码:
class foo {
static $bar = 'baz';
}
var_dump('foo'::$bar);
它在 PHP5 中抛出一个错误(正如预期的那样):
Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in [...][...] on line 4
但它在 PHP7 中没有问题并输出:
string(3) "baz"
这是故意的还是错误?
目前我在文档中找不到任何内容,但我怀疑这可能是预期的行为。
考虑 PHP 5 中的以下内容且没有错误:
function hello()
{
echo "hi";
}
$hi = 'hello';
$hi();
$hi
是一个字符串,因此他们似乎只是决定添加对临时字符串的支持。
'hello'();
在 PHP7
更新
您可以在 http://php.net/manual/en/functions.variable-functions.php
示例的底部找到对 PHP 7.0.0 的小参考我认为这是因为他们重写了有关评估的内容。
像下面这样在 PHP5 中是不可能的,但在 PHP 7 中是不可能的:
echo (new X)->toString();
同样适用于
echo ('X')::$bar
见Changes to the handling of indirect variables, properties, and methods
这主要是关于从左到右的评估,但它也会影响总体评估。
可以在 PHP RFC: Uniform Variable Syntax (Status: implemented) - Thanks to
This RFC proposes the introduction of an internally consistent and complete variable syntax. To achieve this goal the semantics of some rarely used variable-variable constructions need to be changed.
PHP 多年来一直在努力的大方向是在可变变量、可变函数和可变 classes 的使用方面更加灵活和通用。在PHP5中,当你想使用一个变量class时,你必须将class名称放在一个变量中:
$class = 'foo';
echo $class::$foo;
看起来 PHP7 使它更通用,允许任何表达式,而不是需要变量。例如,你可以这样写:
$c1 = 'f';
$c2 = 'oo';
echo ($c1 . $c2)::$foo;