Yii Framework Forum

Followup from a previous question


(Kpsklab) #1

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.
This is followup from Custom router question

I also tried:

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

Thanks.


(Kpsklab) #2

I figured it out, when using the splat operator, I need a new instance, so here is what worked:

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));
    }

(Kpsklab) #4

@ machour

What had you replied, I appreciated your thoughts on previous question.