2

I need to call a function with arguments array, but call_user_func_array seems to be very slow for me. I tried to use ReflectionFunction for that (see code ex. 1), but maybe there is another methods for that? It will be perfectly, if that method supports sorted parameters (see code ex. 2)


code ex. 1

private static function call(Callable $callable, array $args) {
    if(class_exists('ReflectionFunction', false)) {
        $r = (new ReflectionFunction($callable))->invokeArgs($args);
        # ROUTES_CALLBACK_STRATEGY may be "call" or "echo"
        if(defined('ROUTES_CALLBACK_STRATEGY') && strtolower(ROUTES_CALLBACK_STRATEGY) == 'call') {
            return;
        } else {
            echo $r;
        }
    } else {
        call_user_func_array($callable, $args);
    }
}

code ex. 2

$args = array(
    'param1' => 'p1',
    'param2' => 'p2',
    'custom_name' => 'c_n'
);

$callback = function($param, $other_param, $foo) {
    echo $param . " " . $other_param . " " . $foo; // output: p1 p2 c_n
}

$callback2 = function ($custom_name, $param1, $param2) {
    echo $custom_name . " " . $param1 . " " . $param2; // output: c_n p1 p2
}


Thanks for help.

5
  • 1
    What do you mean by call_user_func_array is "slow"? Commented Sep 28, 2015 at 19:08
  • @RocketHazmat using call_user_func_array is 124% slower than calling function directly (function()), calling with ReflectionFunction is 109% slower. Commented Sep 28, 2015 at 19:12
  • Before PHP 5.6, it seems like call_user_func_array was the way to go. Not sure of any other method (other than ReflectionFunction, which I always thought was even slower). Commented Sep 28, 2015 at 19:19
  • 1
    You could use func_get_args within your callable Commented Sep 28, 2015 at 21:28
  • @ElefantPhace thanks for your suggestion, but it's will be hard to migrate :-( Commented Sep 29, 2015 at 7:00

1 Answer 1

1

If you are using PHP 5.6, you can use the ... operator when calling your function.

$callable(...$args);

DEMO: https://3v4l.org/5KUNA

Sign up to request clarification or add additional context in comments.

1 Comment

great suggestion, but I need to support PHP 5.5, and many users of this on 5.3-5.5, not 5.6.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.