Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP call_user_func on a static method

I am developing on Symfony2 and I need to call a method on a class, both known only at runtime.

I have already successfully used variable functions and call_user_func in the project, but this time they give me problems...

My code looks like this

namespace MyBundleNamespace;

use MyBundle\Some\Class;

class MyClass
{
    public static function myFunction() { ... }
}

and in some other file I need to do this

MyClass::myFunction();

but dynamically, so I tried both

$class = "MyClass";
$method = "myFunction";

$class::$method();

and

$class = "MyClass";
$method = "myFunction";
call_user_func("$class::$method");

But I get a class MyClass not found error. Of course the class is included correctly with use and if I call MyClass::myFunction() just like that it works.

I also tried to trigger the autoloader manually like suggested in this question answer comment, but it did not work. Also, class_exists returned false.

What am I missing? Any ideas?

Thanks!

like image 708
mokagio Avatar asked May 10 '12 12:05

mokagio


People also ask

Can static methods be Redeclared?

Yes there's a workaround: use another name. ;-) PHP is not C++, methods are unique by their names, not by their name/arguments/visibility combination. Even then, you cannot overload an object method to a static method in C++ either.

Can static methods be overridden PHP?

Here comes the call of static method with static keyword. In case there is no overridden function then it will call the function within the class as self keyword does. If the function is overridden then the static keyword will call the overridden function in the derived class.

Can we use this in static method PHP?

You can't use $this inside a static function, because static functions are independent of any instantiated object. Try making the function not static. Edit: By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.

Can static method be called by object PHP?

A property declared as static can not be accessed with an instantiated class object (though a static method can). This is why you are able to call the method on an instance, even though that is not what you intended to do.


1 Answers

You're missing the namespace:

$class = '\\MyBundleNamespace\\MyClass';
$method = 'myFunction';

Both calls should work:

call_user_func("$class::$method");
call_user_func(array($class, $method));
like image 193
Jakub Zalas Avatar answered Oct 04 '22 03:10

Jakub Zalas