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.
PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.
Variable-length argument lists, makes it possible to write a method that accepts any number of arguments when it is called. For example, suppose we need to write a method named sum that can accept any number of int values and then return the sum of those values.
To get the number of arguments that were passed into your function, call func_num_args() and read its return value. To get the value of an individual parameter, use func_get_arg() and pass in the parameter number you want to retrieve to have its value returned back to you.
The gettype() function is an inbuilt function in PHP which is used to get the type of a variable. It is used to check the type of existing variable. Parameter: This function accepts a single parameter $var. It is the name of variable which is needed to be checked for type of variable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With