PHP: variable-length argument list by reference?

╄→гoц情女王★ 提交于 2019-11-26 21:08:48

问题


Is it possible to create a PHP function that takes a variable number of parameters all of them by reference?

It doesn't help me a function that receives by reference an array of values nor a function that takes its arguments wrapped in an object because I'm working on function composition and argument binding. Don't think about call-time pass-by-reference either. That thing shouldn't even exist.


回答1:


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 ;)




回答2:


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



回答3:


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 print 1 2




回答4:


It is possible:

$test = 'foo';
$test2 = 'bar';

function test(){
    $backtrace = debug_backtrace();
    foreach($backtrace[0]['args'] as &$arg)
        $arg .= 'baz';
}

test(&$test, &$test2);

However, this uses call-time pass by reference which is deprecated.




回答5:


Edit: sorry I didn't see you wanted them to be references....all you have to do is pass them as an object.

You can also pass them in an array for example

myfunction(array('var1' => 'value1', 'var2' => 'value2'));

then in the function you simply

myfunction ($arguments) {

echo $arguments['var1'];
echo $arguments['var2'];

}

The arrays can also be nested.



来源:https://stackoverflow.com/questions/1925253/php-variable-length-argument-list-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!