2016-11-13 68 views
4

我在Main目錄中有文件index.php;如何使用名稱空間並在PHP中使用?

還有目錄Helpers裏面Main與類Helper

我試圖在index.php注入Helpers\Helper類爲:

<? 

namespace Program; 

use Helpers\Helper; 


class Index { 

    public function __construct() 
    { 
     $class = new Helper(); 
    } 

} 

但它不工作。

如何使用命名空間和在PHP中使用?

+1

_but不work._究竟如何? –

+0

Phpstorms突出顯示爲紅色'使用' – MisterPi

+0

未定義的命名空間'幫助者' – MisterPi

回答

2

With Your Description, Your Directory Structure should look something similar to this:

Main* 
     -- Index.php 
     | 
     Helpers* 
       --Helper.php 

If You are going by the book with regards to PSR-4 Standards, Your Class definitions could look similar to the ones shown below:

的index.php

<?php 
     // FILE-NAME: Index.php. 
     // LOCATED INSIDE THE "Main" DIRECTORY 
     // WHICH IS PRESUMED TO BE AT THE ROOT OF YOUR APP. DIRECTORY 

     namespace Main;   //<== NOTICE Main HERE AS THE NAMESPACE... 

     use Main\Helpers\Helper; //<== IMPORT THE Helper CLASS FOR USE HERE 

     // IF YOU ARE NOT USING ANY AUTO-LOADING MECHANISM, YOU MAY HAVE TO 
     // MANUALLY IMPORT THE "Helper" CLASS USING EITHER include OR require 
     require_once __DIR__ . "/helpers/Helper.php"; 

     class Index { 

      public function __construct(){ 
       $class = new Helper(); 
      } 

     } 

Helper.php

<?php 
     // FILE NAME Helper.php. 
     // LOCATED INSIDE THE "Main/Helpers" DIRECTORY 


     namespace Main\Helpers;  //<== NOTICE Main\Helpers HERE AS THE NAMESPACE... 


     class Helper { 

      public function __construct(){ 
       // SOME INITIALISATION CODE 
      } 

     } 
+0

我仍然收到錯誤:'在'index.php'中找不到'Class'Main \ Helpers \ Helper' – MisterPi

+0

可能是我應該使用'include() '在命名空間之前? – MisterPi

+0

@MisterPi你必須找到一種方法來自動加載課程或只需要手動使用要麼或包括....郵政已更新,以反映...... – Poiz