PHP 中函数参数的求值顺序
Order of evaluation of function arguments in PHP
PHP 函数参数的求值顺序是否保证始终相同?
谢谢。
来自the manual:
Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.
理论上它可能会在 PHP 的未来版本中发生变化,但我当然不希望它发生变化。
(请不要编写任何依赖它的代码,为了每个人...)
通常,是的。作为 the manual states:
[Function] arguments are evaluated from left to right.
但是有两种极端情况,参数根本不被评估:
未定义函数
$calls = 0;
register_shutdown_function(function () use (&$calls) {
echo $calls;
});
func_does_not_exist($calls++);
此 outputs 0
适用于 PHP 的所有版本。
缺少构造函数,未定义函数的特例
class Foo {}
$bar = 0;
$foo = new Foo($bar++);
echo $bar;
这个outputs 0
on PHP < 7.1, and 1
on PHP >= 7.1. It's been called the "Rasmus optimization", and it occurs only in the case of constructing classes without formal constructors. See also #67829, #54162 and #54170.
综上所述,手册是正确的。对于定义的函数,参数从左到右计算,然后传递给函数。未定义的函数,不存在的构造函数是一种特殊情况,不符合函数的条件,因此调用前的评估本身是未定义的。
PHP 函数参数的求值顺序是否保证始终相同?
谢谢。
来自the manual:
Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.
理论上它可能会在 PHP 的未来版本中发生变化,但我当然不希望它发生变化。
(请不要编写任何依赖它的代码,为了每个人...)
通常,是的。作为 the manual states:
[Function] arguments are evaluated from left to right.
但是有两种极端情况,参数根本不被评估:
未定义函数
$calls = 0;
register_shutdown_function(function () use (&$calls) {
echo $calls;
});
func_does_not_exist($calls++);
此 outputs 0
适用于 PHP 的所有版本。
缺少构造函数,未定义函数的特例
class Foo {}
$bar = 0;
$foo = new Foo($bar++);
echo $bar;
这个outputs 0
on PHP < 7.1, and 1
on PHP >= 7.1. It's been called the "Rasmus optimization", and it occurs only in the case of constructing classes without formal constructors. See also #67829, #54162 and #54170.
综上所述,手册是正确的。对于定义的函数,参数从左到右计算,然后传递给函数。未定义的函数,不存在的构造函数是一种特殊情况,不符合函数的条件,因此调用前的评估本身是未定义的。