svgrafov
svgrafov

Reputation: 2014

php list() undefined behaviour

I came across this line:

list($diff, $current, $concurrent) = $diff;

Documentation states that this should result in undefined behaviour. What are the possible variants of this behaviour? Variable $diff is array, containing 3 elements with variable content.

This line is part of application that contains a bug and author of this line is unavailable. Though I am almost sure that it is not what I am looking for, it would be nice to be 100% sure. I am using PHP 5.6.25 as FPM/FastCGI. Thanks in advance.

Upvotes: 0

Views: 166

Answers (1)

Striezel
Striezel

Reputation: 3758

As the documentation for list() also states:

In PHP 5, list() assigns the values starting with the right-most parameter. In PHP 7, list() starts with the left-most parameter.

In other words: This line might work as intended in PHP 5, because the variable $diff that appears on both sides is the last variable to get assigned. However, in PHP 7 the $diff variable gets assigned first, so $diff has already changed by the time the assignments for $current and $concurrent are done.

In general I think the hint about undefined behaviour relates to the fact that you cannot rely on certain assignments to yield the expected results, if a variable appears on both sides of the = sign. A workaround for the issue could look like this:

list($temp, $current, $concurrent) = $diff;
$diff = $temp;
unset($temp);

This way you avoid the undefined behaviour.

Upvotes: 1

Related Questions