2012-09-08 63 views
0

我試圖做這樣的事情:使用變量名實例化一個類

$controller = new $controller . 'Controller';

這將創建PagesController類的新實例,如果$controllerPages。然而,我得到這個錯誤:

Fatal error: Class 'Pages' not found in C:\xampp\htdocs\test\application\app.php on line 25 

該類被命名爲PagesController

我以前在PHP中看到過這樣做,但我找不到任何文檔。

+0

什麼版本的PHP? –

回答

4

做這個

$controller = $controller . 'Controller'; 
$controller = new $controller(); 
+0

與上面相同的錯誤:'可捕獲的致命錯誤:類PagesController的對象無法轉換爲字符串' –

+0

這是如何做到這一點的正確方法。它是什麼行給錯誤?你在構造函數中做什麼? – Kris

0

嘗試:

$controller .= 'Controller'; 
$controller = new $controller(); 

文檔:
Constructors and Destructors
Variable variables

+0

第一種方法導致語法錯誤,但第二種方法產生此錯誤'可捕獲的致命錯誤:類PagesController的對象無法轉換爲字符串'。 –

+0

這個錯誤是否發生在你寫'$ controller = new $ controller;'的行上? – Jocelyn

+0

對不起,這是一個不同的線路來檢查錯誤,我死了()''ing'$ controller'。這個解決方案畢竟有效,儘管克里斯在你面前幾分鐘發佈了它,所以我會接受他的回答。謝謝! –

0

以上的答案,如果你指定完整的命名空間只會工作,無論您使用o r之前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 
相關問題