10

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!

2
  • 1
    Have you tried call_user_func(array($class, $method));? Commented May 10, 2012 at 12:55
  • Yes I did, result was the same. Commented May 10, 2012 at 13:39

1 Answer 1

29

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));
Sign up to request clarification or add additional context in comments.

5 Comments

Yeah it worked! I prefer the variable function way so I used: $namespace = "MyNamespace"; $class = "$namespace\\MyClass"; $method = "myMethod"; $class::$myMethod();
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?
Sure. If you don't specify the namespace (or import it with "use") current one is used.
Well I know that, but the use MyNameSpace\MyClass; was already in the file...
The string gets passed to the global namespace. call_user_func doesn't have access to the use statement in the place it was called from

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.