2013-01-14 70 views
2

我不知道如何解釋它,但我會盡我所能。好吧,我有這三個文件:實例化一個對象到一個名字空間的類

  • Theme.php

    path: /shared/models/Theme.php 
    class: Theme 
    namespace: namespace models; 
    
  • Custom.php

    path: /themes/default/Custom.php 
    class: Custom 
    namespace: this class does not use namespace 
    
  • 的settings.php

    path: /controllers/Settings.php 
    class: Settings 
    namespace: this class does not use namespace 
    

在我Settings.php樣子:

<?php 
class Settings 
{ 
    public function apply() 
    { 
     $theme = new \models\Theme(); 
     $theme->customize(); // in this method the error is triggered 
    } 
} 

現在,看看下面Theme類:

<?php 
namespace models; 

class Theme 
{ 
    public function customize() 
    { 
     $ext = "/themes/default/Custom.php"; 
     if (file_exists($ext)) 
     { 
      include $ext; 
      if (class_exists('Custom')) 
      {    
       $custom = new Custom(); 
       //Here, $custom var in null, why??? 
      } 
     } 
    } 
} 

當我執行的代碼,我收到以下錯誤:

Message: require(/shared/models/Custom.php) [function.require]: failed to open stream: No such file or directory 
Line Number: 64 

爲什麼解釋器試圖從另一個目錄加載Custom類而不是用$ext var?

回答

3

當在命名空間的一個類中調用new Custom()時,您實際上試圖實例化\models\Custom。既然你說你的Custom類「沒有命名空間」,請嘗試使用new \Custom()

您收到的錯誤似乎來自某些嘗試爲\models\Custom要求類文件並失敗的類自動加載器。

+0

是的,你是完全正確的。記住這一點非常重要:'因爲你說你的自定義類沒有名字空間,所以試試新的\ Custom()。「謝謝你:) – manix

相關問題