Home » Php » symfony – PHP call_user_func on a static method

symfony – PHP call_user_func on a static method

Posted by: admin July 12, 2020 Leave a comment

Questions:

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!

How to&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));