37

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
sgibbons
  • 3,620
  • 11
  • 36
  • 31

5 Answers5

42

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);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
21

You can use call_user_func_array() to achieve that:

call_user_func_array("range", $args); to use your example.

Greg
  • 316,276
  • 54
  • 369
  • 333
  • 2
    This looks like an old answer - using the argument unpacking operator is probably more appropriate now, see @Salvador Dali's answer – jgivoni Nov 14 '19 at 15:42
  • Agree with @jgivoni. The general trend in PHP, first seen in 7, and now PHP 8, is to move away from uncontrolled functions such as `call_user_func_array()`, `func_get_args()`, etc., in favor of the variadics operator "...". Now ... I would be much obliged if someone could tell me how to do this in python: $m = 'getName'; $name = $obj->$m(); – dougB Dec 02 '20 at 07:58
9

In certain scenarios, you might consider using unpacking, which is possible in php, is a similar way to python:

list($min, $max) = [3, 6];
range($min, $max);

This is how I have arrived to this answer at least. Google search: PHP argument unpacking

Oleg Belousov
  • 9,981
  • 14
  • 72
  • 127
3

You should use the call_user_func_array

call_user_func_array(array(CLASS, METHOD), array(arg1, arg2, ....))

http://www.php.net/call_user_func_array

or use the reflection api http://www.php.net/oop5.reflection

andy.gurin
  • 3,884
  • 1
  • 21
  • 14
2
<?php

function add(int ...$arr) {           // typehint ready
    return array_sum($arr);
}

var_dump(add(1, 2, 3, ...[1, 2, 3])); // int(12)

Another example with ... - operator.
RFC: https://wiki.php.net/rfc/variadics

lov3catch
  • 133
  • 1
  • 2
  • 11