Variable-length argument variables in functions

In PHP you can do this:

function something() { foreach (func_get_args() as $arg) echo $arg; } something(1, 3); //echoes "13" 

This works great for arguments passed by value, but what if I want them to be passed by reference? eg:

 function something_else() { foreach (func_get_args() as $arg) $arg *= 2; } $a = 1; $b = 3; something_else($a, $b); echo $a . $b; //should echo "26", but returns "13" when I try it 

Is this possible in PHP?

+4
source share
3 answers

The question seems horrible, but it allows you to humor. Below is a terrible hack , but you can send one argument containing the elements you want to work with.

 function something_else($args) { foreach ($args as &$arg) { $arg *= 2; } } $a = 1; $b = 3; something_else(array(&$a, &$b)); echo $a . $b; // 26 
+2
source

No. You can not. The prameter declaration passed to ref is explicitly specified as function something(&$arg1, &$arg2) . If you do not know the number of parameters at compile time, you can do something like this:

 function something_else($args) { foreach ($args as $arg) $GLOBALS[$arg] *= 2; } $a = 1; $b = 3; something_else(array('a', 'b')); echo $a . $b; //returns "26" 

Basically, the code passes functions to the parameter names that the function will change. $GLOBALS contains references to all defined variables in the global scope of the script. This means that if the call is made from another function, it will not work:

 function something_else($args) { foreach ($args as $arg) $GLOBALS[$arg] *= 2; } function other_function(){ $a = 1; $b = 3; something_else(array('a', 'b')); echo $a . $b; //returns "13" } other_function(); 

triggers notifications undefined indices a and b . Thus, another approach is to create an array with references to variables that the function will change as:

 function something_else($args) { foreach ($args as &$arg) $arg *= 2; } function other_fucntion(){ $a = 1; $b = 3; something_else(array(&$a, &$b)); echo $a . $b; //returns "26" } other_fucntion(); 

Pay attention to & on the foreach line. This is necessary so as not to create a new variable, iterating over the array. PHP> 5 required for this function.

+1
source

You can do it this way, but it uses a call-time pass from a link that is deprecated in PHP 5.3:

 function something_else() { $backtrace = debug_backtrace(); foreach($backtrace[0]['args'] as &$arg) $arg *= 2; } $a = 1; $b = 3; something_else(&$a, &$b); echo $a . $b; 
+1
source

All Articles