Take the 2-minute tour ×

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


but dynamically, so I tried both

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



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

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?


share|improve this question
Have you tried call_user_func(array($class, $method));? –  prehfeldt May 10 '12 at 12:55
Yes I did, result was the same. –  mokagio May 10 '12 at 13:39

1 Answer 1

up vote 3 down vote accepted

You're missing the namespace:

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

Both calls should work:

call_user_func(array($class, $method));
share|improve this answer
Yeah it worked! I prefer the variable function way so I used: $namespace = "MyNamespace"; $class = "$namespace\\MyClass"; $method = "myMethod"; $class::$myMethod(); –  mokagio May 10 '12 at 13:29
Could you please tell me why I had to add the namespace? Is it related to the fact that the whole thing is evaluated runtime? –  mokagio May 10 '12 at 13:33
Sure. If you don't specify the namespace (or import it with "use") current one is used. –  Jakub Zalas May 10 '12 at 16:12
Well I know that, but the use MyNameSpace\MyClass; was already in the file... –  mokagio May 10 '12 at 21:12

Your Answer


