jam-jam
jam-jam

Reputation: 31

PHP : Method defined in _call and called with call_user_func_array

I have a similar question to this one : PHP can I call unexistent function with call_user_func

I need to call a method defined width __call but i don't know how many parameter to pass. So I am using this :

call_user_func_array(array($object, $method_name), $arguments);

But it doesn't work. Actually, this works :

$object->$method_name();

But i don't know how to pass parameter by an other way that call_user_func_array...

I wan't something like :

$object->$method_name($arguments[0], $arguments[1], $arguments[2] /*,... until no more args*/);

An idea ? Thank you

Upvotes: 1

Views: 64

Answers (1)

rickdenhaan
rickdenhaan

Reputation: 11328

This is perfectly possible. I don't know your code, but here's a quick test I put together to make sure it works:

class Foo {
    function _bar($arg1, $arg2) {
        print_r(func_get_args());
    }

    function __call($name, $args) {
        call_user_func_array([$this, '_'.$name], $args);
    }
}

$foo = new Foo();
$func = 'bar';

call_user_func_array([$foo, $func], ['1', '2']);

// Array
// (
//     [0] => 1
//     [1] => 2
// )

This tries to call the function Foo::bar() which doesn't exist, so it ends up in Foo::__call(), which then calls Foo::_bar().

Upvotes: 2

Related Questions