Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use call_user_func for static class method?

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.

like image 897
B Seven Avatar asked Mar 10 '12 23:03

B Seven


1 Answers

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.

like image 112
hakre Avatar answered Oct 12 '22 19:10

hakre