Search code examples
phpvariadic-functions

PHP - call __invoke with a variable number of arguments


Is it possible, with some kind of dirty trick possibly, to invoke a class via the __invoke magic method using a variable number of arguments?

I know that in php 5.6 there are variadics, but my version is not there yet...

For a normal class method I could try to do something using the magic method __call and the call_user_func_array function. What about the __invoke magic method?


Solution

  • Seems to be possible with func_get_args():

    Adjusting the example from the docs:

    <?php
    class CallableClass
    {
        public function __invoke()
        {
            var_dump(func_get_args());
        }
    }
    $obj = new CallableClass;
    $obj(5, 6, 7, 8); // vary arguments to meet your needs