oscurodrago
oscurodrago

Reputation: 808

Magic Methods __Call doesn't work well with multiple arguments

I have a problem with magic method __call

The following code works well, except when there is more than one argument in the call of method. I've tried different solutions without any good result (just $args or implode(', ' $args) doesn't work)

public function __call($method, $args) {
    if($this->methods[$method] != NULL)
            return $this->objects[$this->methods[$method]]->$method($args[0]);
    else    trigger_error("Call undefined method " . $this->class . "::" . $method, E_USER_ERROR);
}

That works too if I write it like this:

return $this->objects[$this->methods[$method]]->$method($args[0], $args[1], $args[3]);

But as you can see this isn't correct because a function can have 0 to infinite arguments.

Do you know how fix the script for multiple arguments?

Upvotes: 0

Views: 2444

Answers (2)

Julio Popócatl
Julio Popócatl

Reputation: 782

Try this:

public function __call($method, $parameters){

    if (in_array($method, ['get', 'post'])) {
        return $this->$method(...$parameters);
    }
}

Upvotes: 0

deceze
deceze

Reputation: 522109

return call_user_func_array($this->objects[$this->methods[$method]]->$method, $args);

See http://php.net/call_user_func_array.

Upvotes: 8

Related Questions