3

RT

function 1 :

$class->$func()

function 2:

//Simple callback
call_user_func($func)
//Static class method call
call_user_func(array($class,$func))
//Object method call
$class = new MyClass();
call_user_func(array($class, $func));

Is there a difference? I want to see the sourcecode(https://github.com/php/php-src) should we do?

1
  • 1
    There's no differences in the ways you've presented of calling an object method. What's your question anyway? Commented Sep 7, 2012 at 4:06

1 Answer 1

6

call_user_func_array is very slow performance-wise, that's why in many cases you want to go with explicit method call. But, sometimes you want to pass arbitrary number of arguments passed as an array, e.g.

public function __call($name, $args) {
    $nargs = sizeof($args);
    if ($nargs == 0) {
        $this->$name();
    }
    elseif ($nargs == 1) { 
        $this->$name($args[0]);
    }
    elseif ($nargs == 2) { 
        $this->$name($args[0], $args[1]);
    }
    #...
    // you obviously can't go through $nargs = 0..10000000, 
    // so at some point as a last resort you use call_user_func_array
    else { 
        call_user_func_array(array($this,$name), $args);
    }
}

I'd go with checking $nargs up to 5 (it's usually unlikely that a function in PHP accepts more than 5 arguments, so in most cases we will call a method directly without using call_user_func_array which is good for performance)

The result of $class->method($arg) is the same as call_user_func_array(array($class,'method'), array($arg)), but the first one is faster.

Sign up to request clarification or add additional context in comments.

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.