Skip to content
Advertisement

PHP: How to spread an array as function parameters

I’m trying to use __callStatic to wrap the calls to differents static functions in my class.

This current version of the code allows me to do so with functions that have 0 or 1 parameter:

class test {

  public static function __callStatic($name, $args) {
    if (method_exists(__CLASS__, $name)) {
      echo "it does existn";
      return forward_static_call([__CLASS__, $name], $args[0]);
    } else {
      echo "it does not existn";
    }
  }

  private static function mfunc($param1, $param2) {
    echo "that's my func n";
    echo "$param1n";
    echo "$param2n";
  }

}
test::notafunc("one", 'two');
test::mfunc("one", "two");

However it will fail for mfunc since it has two parameters. How can i spread the different arguments when i’m calling the function ?

I can’t use the new spread operator because I am locked on PHP 7.2. I can’t modify mfunc either, because I have way too much methods to change in the project.

Advertisement

Answer

The spread operator is still usable in PHP 7.2, what you point to is something slightly different (it’s about being able to use it as part of an array). So you can use

return forward_static_call([__CLASS__, $name], ...$args);

As a more legible version…

return static::{$name}(...$args);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement