PHP call_user_func by static method

I am developing Symfony2 and I need to call a method in a class that is known only at runtime.

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

My code is as follows

 namespace MyBundleNamespace; use MyBundle\Some\Class; class MyClass { public static function myFunction() { ... } } 

and in another 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 class MyClass not found . Of course, the class is included correctly with use , and if I call MyClass::myFunction() in the same way that it works.

I also tried to start the autoloader manually, as suggested in this question to answer a comment, but that did not work. In addition, class_exists returned false .

What am I missing? Any ideas?

Thanks!

+4
source share
1 answer

You are missing a namespace:

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

Both calls should work:

 call_user_func("$class::$method"); call_user_func(array($class, $method)); 
+13
source

Source: https://habr.com/ru/post/1411773/


All Articles