untymage's avatar

Splat args into method when using container

I need to call a method without prior knowledge of its parameter names. The method I want to call takes varying parameter names, and I must generate arguments on-the-fly. Consider this method structure:

class MyClass
{
    public function handle($arg1, $arg2, $input3)
    {
		//
    }
}

How to splat args like:

$args = [1, 2, 'test'];

app()->call([new MyClass, 'handle'], [...$args])

But not working:

Unable to resolve dependency [Parameter #0 [ <required> $arg1 ]] in class \MyClass

I have the arguments, But don't know the class parameter's name, is it possible to splat them with container?

0 likes
2 replies
martinbean's avatar

@untymage Show the actual code. Because it makes no sense to try and bind something to the container if you don’t actually know the arguments it needs in order to be able to build that service.

jlrdw's avatar

Look at some code in the framework and see how Taylor uses splat.

One example I use in another framework:

    public static function __callStatic($method, $params)
    {
        $instance = \Model\Account::class;
        $c = new $instance;
        return $c->$method(...array_values($params));
    }

Also see https://www.php.net/manual/en/migration56.new-features.php

Please or to participate in this conversation.