简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM