2016-11-15 24 views
0

所以我有一個config.php文件有以下幾點:在包括PHP文件中使用「使用」

use PHPOnCouch\Couch; 
use PHPOnCouch\CouchAdmin; 
use PHPOnCouch\CouchClient; 

然後我呼籲其他文件讓我們說index.php包括的config.php

require_once("config.php"); 
include("page.php"); 

然後我有page.php使用CouchClient像這樣:

$client = new couchClient ($URL, $DB); 

但在page.php文件,我得到以下錯誤:

Fatal error: Class 'couchClient' not found in page.php

不應該在該頁面連接到我的config.php文件讓我沒有把這個在我的page.php

+2

您需要在要使用這些類的文件中添加'use'。 'use'語句不會被繼承.. –

+0

好的,謝謝@MagnusEriksson - 希望有一種方法可以讓它們繼承。 – bryan

+0

請參閱此問題http://stackoverflow.com/questions/10965454/how-does-the-keyword-use-work-in-php-and-can-i-import-classes-with-it –

回答

3

page.php

$client = new \PHPOnCouch\CouchClient ($URL, $DB);

use PHPOnCouch\CouchClient; 
$client = new CouchClient ($URL, $DB); 

這也適用

use PHPOnCouch\CouchClient as SomeOtherFunnyName; 
$client = new SomeOtherFunnyName ($URL, $DB); 

,並在PHP閱讀更多關於namespaces

小更新:

Shouldn't this page be connected to my config.php so that I don't have to put this in my page.php?

  • 每一個包括都有自己的本地namesless命名空間或一個/多個命名的命名空間!
  • 如果沒有給出名稱空間,那麼您有一個無名稱的名稱空間。 換句話說,您總是可以在php腳本中使用namespace { /*code*/ }
  • 如果您位於名稱空間中,則必須通過use包含所有需要的類。 因爲所有文件都有自己的名稱空間,所以您必須通過use
  • 將其包含在名稱空間中:namespace xyz;沒有大括號,僅適用於只包含一個名稱空間的文件!

簡單〔實施例(只有一個文件):

namespace a { 
     class a {} 
    } 
    namespace b { 
     use a\a; 
     class b extends a{} 
    } 
    namespace { 
     use a\a; 
     use b\b; 
     new a; 
     new b; 
    } 

可以說,過去的命名空間的心不是給定的,我們有這樣的一個新的文件,我們可以做

namespace mynamespace; 
    use a\a; 
    use b\b as x; 
    new a; 
    new x; 
+0

@Magnus Eriksson是的,看到它,更新;-) – JustOnUnderMillions