3

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?

0

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

You can use rest operator:

public function __invoke(...$args)
{
    print_r($args);
}

Comments

0

PHP doesn't seem to mind if you add the arguments to the invoke method.

So this would also work:

<?php

class Invoked
{
    public function __invoke($value, $key)
    {
        var_dump($value, $key);
    }
}

$numbers = range(0, 10);

array_walk($numbers, new Invoked);

Comments

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.