views:

399

answers:

4

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.

A: 

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

BojanG
A: 

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.

I actually am still not 100% sure what your trying to ask, but I hope I understood correctly.
The question is simple. The hard thing is to explain why passing the arguments wrapped in an array or in an object don't serve my needs (I's a thing about argument binding and function composition).
GetFree
+1  A: 

PHP has no buildin function for variable parameters by reference. But object are always passed by reference. (Since php5 that is)

However its possible to:

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

The "..." is not php syntax, you'll have to type them in. So you'll always have a maximum amount of parameters. 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 ;)

Bob Fanger
Yes, I thought of doing that. It seems the only solution so far. Not very elegant, but it works.
GetFree