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-TypeDocs.
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, 2022Comments
-
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 about 12 yearsWell 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 about 12 yearsBoth throw
... [function.call-user-func]: First argument is expected to be a valid callback in ...
-
hakre about 12 yearsWell, 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 about 12 yearsOK, that worked. It needs
static
beforefunction TestGetServer()
inclass LibraryTests
. Thanks.