Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jlrdw's avatar
Level 75

PHP general question

This works:

if (array_key_exists($key_to_check, $routes)) {
            $uparts = explode('@', $routes[$key_to_check]);
            $controller = isset($uparts[0]) ? $uparts[0] : null;
            $action = isset($uparts[1]) ? $uparts[1] : null;
            call_user_func_array(array($controller, $action), $last);
        }

But I am trying to convert to variadic (splat operator), and the below does not work:

if (array_key_exists($key_to_check, $routes)) {
            $uparts = explode('@', $routes[$key_to_check]);
            $controller = isset($uparts[0]) ? $uparts[0] : null;
            $action = isset($uparts[1]) ? $uparts[1] : null;
            $controller->$action(...$last);
        }

Anyone know how to properly replace the call_user_func_array with splat?

Note, $last is just the parameters being passed.

0 likes
2 replies
Cronix's avatar
Cronix
Best Answer
Level 67

It doesn't replace call_user_func_array(). It replaces func_get_args(). It's just a way to pass an unknown number of arguments to any function (packing) or retrieving them from the function (unpacking). See the examples and explanation in the announcement: http://php.net/manual/en/migration56.new-features.php

jlrdw's avatar
Level 75

Anyone wanting to use this, I figured it out, a question about the php video series made me work on a router I have put on hold.

if (array_key_exists($key_to_check, $routes)) {
            $uparts = explode('@', $routes[$key_to_check]);
            $controller = isset($uparts[0]) ? $uparts[0] : null;
            $action = isset($uparts[1]) ? $uparts[1] : null;
            self::load($controller, $action, $last);
        } else {
            $c = new \Mini\Controller\HomeController();
            $action = 'index';
            $c->$action();
        }
    }

    public static function load($controller, $action, $last = array())
    {
        $c = new $controller;
        return $c->{$action}(...array_values($last));
    }

I notice that call_user_func_array does not need the new keyword, but splat does. Thanks @cronix you get best answer, I appreciate when you reply, and you have brought me up to date on arrays, well kinda.

Very tricky to loop some of them.

I am still tweaking this router, I will post all in a guide when finished.

I am basically updating a custom framework.

Edit: Either of these work:

return $c->$action(...array_values($last));

and

return $c->{$action}(...array_values($last));

I notice Taylor wraps the method or action in the curly braces.

Please or to participate in this conversation.