2016-11-13 4 views
4

ディレクトリMainにファイルindex.phpがあります。PHPで名前空間を使用するには?

ディレクトリHelpers の中にHelperのディレクトリもあります。

私はとしてindex.phpでクラスHelpers\Helperを注入しようとした:

<? 

namespace Program; 

use Helpers\Helper; 


class Index { 

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

} 

しかし、それは動作しません。

PHPで名前空間を使用するには?

+1

それがどのように正確にwork._しない_But? –

+0

Phpstormsはこの 'use 'のように赤く強調表示します – MisterPi

+0

未定義の名前空間' Helpers' – 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

私はまだエラーが発生します: 'Class' Main \ Helpers \ Helper 'が' index.php'に見つかりません – MisterPi

+0

'include() '名前空間の前に? – MisterPi

+0

@MisterPiクラスを自動読み込みする方法を見つける必要があります。単にrequireまたはincludeを使用して手動で要求する必要があります。.... – Poiz

関連する問題