0

I want to use a variable class name in PHP with a prefixed namespace.

Three variants I have tried produce expectation of an identifier error after the last backslash.

(\api\controllers\(new $class()))->{$method}($this->id);

((new \api\controllers\$class()))->{$method}($this->id);

((new \api\controllers\{$class()}))->{$method}($this->id));

How do I make this work?

4
  • What exactly are you trying to accomplish? It seems like you might be jumping through hoops that you could simply walk around instead... Commented Apr 15, 2019 at 16:43
  • If this is a requirement for your application, you should probably rethink the structure of your application. Commented Apr 15, 2019 at 16:43
  • I want to pick up the class name in the desired namespace matching other file name in another namespace. I have use command available but I am trying to see if this will work. Please clarify the drawbacks to this approach. Since I use an autoloader I have switched order of autloaded directories which eliminates the class name addressing in this fashion need for this in the present script. Commented Apr 15, 2019 at 16:44
  • @GregSchmidt, please see stackoverflow.com/questions/55680983/… for context to my application Commented Apr 15, 2019 at 16:51

1 Answer 1

1

How about this:

$full_class_name = '\api\controllers\' . $class;
$controller = new $full_class_name();
$controller->{$method}($this->id);

It can probably be shortened somewhat, but doing that here would perhaps make the answer more obscure and less helpful.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that makes sense, I was overlooking the fact that my $class variable was being added to the end of a literal namespace path. That's why it didn't work.

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.