PHP: variable-length argument list by reference? PHP: variable-length argument list by reference? php php

PHP: variable-length argument list by reference?


PHP 5.6 introduced new variadic syntax which supports pass-by-reference. (thanks @outis for the update)

function foo(&...$args) {    $args[0] = 'bar';}

For PHP 5.5 or lower you can use the following trick:

function foo(&$param0 = null, &$param1 = null, &$param2 = null, &$param3 = null, &$param4 = null, &$param5 = null) {  $argc = func_num_args();  for ($i = 0; $i < $argc; $i++) {    $name = 'param'.$i;    $params[] = & $$name;  }  // do something}

The downside is that number of arguments is limited by the number of arguments defined (6 in the example snippet). but with the func_num_args() you could detect if more are needed.

Passing more than 7 parameters to a function is bad practice anyway ;)


PHP 5.6 introduces a new variadic syntax that supports pass-by-reference. Prefixing the last parameter to a function with ... declares it as an array that will hold any actual arguments from that point on. The array can be declared to hold references by further prefixing the ... token with a &, as is done for other parameters, effectively making the arguments pass-by-ref.

Example 1:

function foo(&...$args) {    $args[0] = 'bar';}foo($a);echo $a, "\n";#  output:#a

Example 2:

function number(&...$args) {    foreach ($args as $k => &$v) {        $v = $k;    }}number($zero, $one, $two);echo "$zero, $one, $two\n";#  output:#0, 1, 2


You should be able to pass all of your parameters wrapped in an object.

Class A{    public $var = 1;}function f($a){    $a->var = 2;}$o = new A;printf("\$o->var: %s\n", $o->var);f($o);printf("\$o->var: %s\n", $o->var);

should print12