Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:
args = [3, 6] range(*args) # call with arguments unpacked from a list
This is equivalent to:
range(3, 6)
Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?
The unpack() function unpacks data from a binary string.
PHP doesn't support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control back to the calling function and second return statement will never get executed.
PHP Function Arguments Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.
In php5.6
Argument unpacking via ...
(splat operator) has been added. Using it, you can get rid of call_user_func_array()
for this simpler alternative. For example having a function:
function add($a, $b){ return $a + $b; }
With your array $list = [4, 6];
(after php5.5 you can declare arrays in this way).
You can call your function with ...
:
echo add(...$list);
You can use call_user_func_array()
to achieve that:
call_user_func_array("range", $args);
to use your example.
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