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!
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.
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With