How to use call_user_func for static class method?

2019-04-25 11:30发布

The following code works fine.

LibraryTests::TestGetServer();

Get the array of functions in LibraryTests and run them:

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

This throws an error: Warning: call_user_func(LibraryTests::TestGetServer()) [function.call-user-func]: First argument is expected to be a valid callback

Here is the class that is being called:

class LibraryTests extends TestUnit {

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

How to fix?

Working in PHP 5.2.8.

1条回答
三岁会撩人
2楼-- · 2019-04-25 12:11

Either (as of PHP 5.2.3):

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

Or (earlier):

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

See call_user_func­Docs and the Callback Pseudo-Type­Docs.

查看更多
登录 后发表回答