PHP - pass a variable number of arguments by reference

I know that you can pass a variable number of arguments to a function that are accessed individually.

for instance

function foo() { $arg = func_get_arg(0); $arg += 10; } $a = 100; foo($a); echo "A is $a\n"; 

But these arguments are passed by value, as shown above.

Is it possible to use them as if they were passed by reference similarly to functions like bind_param in the mysqli library?

+4
source share
2 answers

First of all, I want to note: Do not use links .

On the side: it is impossible to do this directly, since the engine must know if there is something for the link before calling the function. What you can do is pass an array of links:

 $a = 1; $b = 2; $c = 3; $parameters = array(&$a, &$b, &$c, /*...*/); func($parameters); function func(array $params) { $params[0]++; } 
+1
source

You canโ€™t, you just canโ€™t tell php that itโ€™s a link, but itโ€™s not, but! I recommend doing the following:

 function foo() { $arg = func_get_arg(0); $arg->val += 10; } $a =new stdClass(); $a->val = 100; foo($a); echo "$a\n"; // 110 

you can apply the box to the desired value and it works. I hope you find it useful, if you have any questions, please ask.

+1
source

All Articles