如何对静态类方法使用call_user_func


How to use call_user_func for static class method?

以下代码运行良好。

LibraryTests::TestGetServer();

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

$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中工作。

任一(自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­文档和回调伪类型­文档