2012-05-10 137 views
82

我在命名空間和use語句中遇到了一些問題。PHP名稱空間和「use」

我有三個文件:ShapeInterface.phpShape.phpCircle.php

我試圖做到這一點使用相對路徑,所以我已經把這個所有類:

namespace Shape; 

在我的圈子裏I類有以下幾點:

namespace Shape; 
//use Shape; 
//use ShapeInterface; 

include 'Shape.php'; 
include 'ShapeInterface.php';  

class Circle extends Shape implements ShapeInterface{ .... 

如果我使用include聲明我沒有得到任何錯誤。如果我嘗試use語句,我得到:

Fatal error: Class 'Shape\Shape' not found in /Users/shawn/Documents/work/sites/workspace/shape/Circle.php on line 8

可能有人請給我在這個問題上一些指導?

+0

我讀這一點,還是不太明白這一點。外部文件是否包含在使用中? –

+0

也關於這個問題 - http:// stackoverflow。com/questions/33341955 /不要導入或使用順序影響功能在php – Peter

回答

124

use operator用於爲類,接口或其他名稱空間的名稱提供別名。大多數use語句引用一個命名空間或類,你想縮短:

use My\Full\Namespace; 

等同於:

use My\Full\Namespace as Namespace; 
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo 

如果use運營商與一個類或接口的名稱使用,它具有以下用途:

// after this, "new DifferentName();" would instantiate a My\Full\Classname 
use My\Full\Classname as DifferentName; 

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent 
use ArrayObject; 

use運營商是不是與autoloading混淆。通過註冊一個自動加載器(例如spl_autoload_register),一個類是自動加載的(不需要include)。您可能想要閱讀PSR-4以查看合適的自動加載器實現。

+0

真棒,我檢查出來。謝謝! –

+0

所以,如果我創建另一個名爲bootstrap.php的文件並將自動加載器與$ circle = new Circle()一起放置,它包含了Circle.php,但是我收到了一個錯誤:致命錯誤:Class'Shape'沒有在第6行的.../Circle.php中找到。它似乎加載了Circle.php,但沒有加載Shape.php Circle被定義如下所示:class Circle extends Shape implements ShapeInterface –

+0

如果我從上述類中刪除名稱空間,則自動加載器可以正常工作。然而,當我在形狀類的界面中有命名空間時,我得到上述錯誤 –

4

最簡單的方法把它

如果您需要訂購你的代碼中的命名空間,只需使用關鍵字namespace

在file1.php namespace foo\bar;

在file2.php $obj = new foo\bar\myObj();


還有更多的這個故事一點 - 在use關鍵字。

如果你在文件2中說這意味着你需要在文件的任何地方使用mypath而不是foo\bar

$obj = new mypath\myObj(); 

如果你曾說過use foo\bar它等於use foo\bar as bar