PHP: variable-length argument list by reference?
Is it possible to create a PHP function that takes a variable number of paramet开发者_运维百科ers 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.
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 print 1 2
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.
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.
精彩评论