3

RT

機能1:

$class->$func()

機能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));

違いはありますか?ソースコード( https://github.com/php/php-src )を見たいのですが?

4

1 に答える 1

6

call_user_func_arrayパフォーマンスが非常に遅いため、多くの場合、明示的なメソッド呼び出しを使用する必要があります。しかし、配列として渡された任意の数の引数を渡したい場合があります。

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);
    }
}

私は 5 つまでチェック$nargsします (通常、PHP の関数が 5 つ以上の引数を受け入れる可能性は低いため、ほとんどの場合call_user_func_array、パフォーマンスに優れているメソッドを使用せずにメソッドを直接呼び出します)。

の結果は$class->method($arg)と同じですcall_user_func_array(array($class,'method'), array($arg))が、最初のものの方が高速です。

于 2012-09-07T04:07:07.693 に答える