解決類別/函式/常數命名衝突。傳統做法加前綴(如 Article_Comment)導致名稱冗長、維護困難。命名空間提供隔離機制,類似檔案系統目錄結構。
<?php
// 必須是檔案第一行(前面不能有任何輸出或程式碼)
namespace MyProject\Blog;
class Comment { }
function getTotal() { return 100; }
const VERSION = '1.0';
錯誤示範:namespace 前有 HTML 輸出、變數宣告、甚至空白行都會導致致命錯誤。
<?php
namespace Blog\Article;
class Comment { }
namespace Blog\MessageBoard;
class Comment { }
// 當前空間直接使用
$c1 = new Comment(); // Blog\MessageBoard\Comment
// 跨空間使用完全限定名稱
$c2 = new \Blog\Article\Comment(); // Blog\Article\Comment
| 術語 | 寫法 | 解析方式 | 類比 |
|---|---|---|---|
| 非限定名稱 | Comment | 當前空間 | 檔名 comment.php |
| 限定名稱 | Article\Comment | 相對於當前空間 | 相對路徑 ./Article/comment.php |
| 完全限定名稱 | \Blog\Article\Comment | 絕對路徑 | 絕對路徑 /Blog/Article/comment.php |
<?php
namespace BBS;
use Blog\Article; // 導入空間
use Blog\Article as Art; // 空間別名
use Blog\Article\Comment; // 導入類別
use Blog\Article\Comment as Cmt; // 類別別名
$c1 = new Article\Comment(); // 限定名稱
$c2 = new Art\Comment(); // 別名
$c3 = new Comment(); // 非限定名稱(導入類別後)
$c4 = new Cmt(); // 類別別名
導入衝突:若當前空間已有同名元素,use 會導致致命錯誤,需用別名避開。
<?php
namespace Blog\Article;
class Comment { }
// 1. namespace 關鍵字
$c = new namespace\Comment();
// 2. __NAMESPACE__ 魔術常數
$class = __NAMESPACE__ . '\Comment';
$c = new $class();
// ⚠️ 雙引號轉義陷阱
$bad = __NAMESPACE__ . "\Comment"; // \C 被轉義!
$good = __NAMESPACE__ . '\\Comment'; // 單引號或雙重轉義
// ⚠️ 字串調用永遠視為非限定或完全限定,不支援限定名稱
use Blog\Article\Common;
$obj = new 'Common'; // 錯誤:視為當前空間 Common
$obj = new 'Article\Common'; // 錯誤:視為全域 Article\Common
未宣告 namespace 的程式碼屬於公共空間。呼叫公共空間元素需加前導 \:new \FilterXSS()。PHP 內建類別/函式/常數皆屬公共空間。
Vendor\Package\Component)。