How to use call_user_func for static class method?

10,266

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.

Share:
10,266
B Seven
Author by

B Seven

Status: Hood Rails on HTTP/2: Rails HTTP/2 Rack Gems: Rack Crud Rack Routing Capybara Jasmine

Updated on July 15, 2022

Comments

  • B Seven
    B Seven almost 2 years

    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.

  • hakre
    hakre about 12 years
    Well you need to have a valid callback for that to work. If you put invalid values into $method, it does not work. If you put valid values in there, it does work. Take care that this is for static class methods only.
  • B Seven
    B Seven about 12 years
    Both throw ... [function.call-user-func]: First argument is expected to be a valid callback in ...
  • hakre
    hakre about 12 years
    Well, first of all define the mehtod as static in your class: static function TestGetServer - or work on a class instance with the array notation. I linked two pages from the manual which contain a lot of information and examples and should lead you the way so that you can solve the problem in whichever way suits your needs.
  • B Seven
    B Seven about 12 years
    OK, that worked. It needs static before function TestGetServer() in class LibraryTests. Thanks.