如何使用call_user_func进行静态类方法?

时间:2012-03-10 23:54:08

标签: php reflection callback

以下代码可以正常使用。

LibraryTests::TestGetServer();

获取LibraryTests中的函数数组并运行它们:

$methods = get_class_methods('LibraryTests');
foreach ($methods as $method) {
  call_user_func('LibraryTests::' . $method . '()' );
}

这会引发错误:Warning: call_user_func(LibraryTests::TestGetServer()) [function.call-user-func]: First argument is expected to be a valid callback

这是被调用的类:

class LibraryTests extends TestUnit {

    function TestGetServer() {
        TestUnit::AssertEqual(GetServer(), "localhost/");
    }
    .
    .
    .

如何解决?

使用PHP 5.2.8。

1 个答案:

答案 0 :(得分:13)

(从PHP 5.2.3开始):

$methods = get_class_methods('LibraryTests');
foreach ($methods as $method) {
  call_user_func('LibraryTests::' . $method);
}

或(早先):

$methods = get_class_methods('LibraryTests');
foreach ($methods as $method) {
  call_user_func(array('LibraryTests', $method));
}

请参阅call_user_func­DocsCallback Pseudo-Type­Docs