PHP RFC: list() Reference Assignment


PHP has had list() assignment and reference assignment for a long time. However, it is not currently possible to use reference assignment with list(). This RFC proposes this new syntax to cover this.


Under this proposal, a new syntax is introduced:

$array = [1, 2];
list($a, &$b) = $array;

This would be equivalent to the following:

$array = [1, 2];
$a = $array[0];
$b = &$array[1];

Of course, this works just like list() normally does, so you can use it with nested list() and skip values as well:

$array = [1, 2, 3, [3, 4]];
list(&$a, $b,, list(&$c, $d)) = $array;

It also works with foreach():

$array = [[1, 2], [3, 4]];
foreach ($array as list(&$a, $b)) {
    $a = 7;

The advantage of adding support for this is that it allows you to use reference assignment for multiple variables at once, which is not currently possible. The syntax here is different from the traditional assignment syntax which places the & before the rvar, not the lvar, but the advantage here is that you can reference assign some, but not all of the variables in list().

Backward Incompatible Changes

This introduces no backwards incompatible changes.

Proposed PHP Version(s)

Next PHP 5.x, hopefully 5.6.

Open Issues

My implementation contains a memory leak, which I haven't yet figured out how to fix, when this code is run:

$array = [1, 2];
list(&$a, $b) = $array;
list($b, &$a) = $array;

Any help fixing that issue is appreciated.

Proposed Voting Choices

Merge into PHP 5.6?

  • Yes
  • No

Patches and Tests


Implemented with passing test. However, as mentioned above in “Open Issues”, there is a known memory leak. Hence, it can't yet be considered a final patch.

Any help fixing that issue is appreciated.

EDIT 2014-05-15: I've withdrawn this RFC, due to discovering that PHP's current approach to parsing and opcode output makes this impossible to implement.


(Not merged into PHP)


Rejected Features

None as yet.

rfc/list_reference_assignment.txt · Last modified: 2014/05/15 21:14 by ajf