Reputation: 9008
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?
Upvotes: 3
Views: 3595
Reputation: 11
You can use rest operator:
public function __invoke(...$args)
{
print_r($args);
}
Upvotes: 1
Reputation: 317
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);
Upvotes: 0
Reputation: 72991
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
Upvotes: 2