Vahe
Vahe

Reputation: 1841

Variable classname using namespaces in php

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?

Upvotes: 0

Views: 74

Answers (1)

Greg Schmidt
Greg Schmidt

Reputation: 5098

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.

Upvotes: 1

Related Questions