[英]Using variable names to instantiate a class
我正在嘗試做這樣的事情:
$controller = new $controller . 'Controller';
如果$controller
是Pages
它將創建PagesController
類的新實例。 但是,我收到此錯誤:
Fatal error: Class 'Pages' not found in C:\xampp\htdocs\test\application\app.php on line 25
該類名為PagesController
。
我以前已經在PHP中看到它完成過,但是我找不到關於它的任何文檔。
做這個
$controller = $controller . 'Controller';
$controller = new $controller();
僅當您指定完整的名稱空間時,以上答案才有效,無論您之前使用過use
還是namespace
。
use \App\Article\Health as Health;
$article = new Health; // works fine
$classname = "Health";
$article = new $classname(); // Class 'Health' not found.
$c = "\\App\\Article\\$classname";
$article = new $c(); // works fine
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.