Is order of evaluation of PHP function arguments guaranteed to be always the same?
Thanks.
Usually, yes. As the manual states:
[Function] arguments are evaluated from left to right.
But there are two edge cases where arguments are not evaluated at all:
$calls = 0;
register_shutdown_function(function () use (&$calls) {
echo $calls;
});
func_does_not_exist($calls++);
This outputs 0
on all versions of PHP.
class Foo {}
$bar = 0;
$foo = new Foo($bar++);
echo $bar;
This 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.
In summary, the manual is correct. For defined functions, arguments are evaluated left-to-right then passed into the function. Undefined functions, for which a non-existent constructor is a special case, do not qualify as functions and so the evaluation before calling is itself undefined.
From 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.
In theory it might change in future versions of PHP, but I certainly wouldn't expect it to.
(And please don't write any code that relies on it, for everyone's sake...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With