How to use call_user_func for static class method?

2019-04-25 11:35发布

问题:

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:

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.