解決**類別/函式/常數命名衝突**,實現**程式碼模組化**、支援**自動載入 (PSR-4)**、構建**可維護的分層架構**。無命名空間時,專案需用前綴區分(如 Project_Module_Class),極其繁瑣且易衝突。
<?php
// 檔案**第一行非註解程式碼**必須是 namespace(前面不能有輸出、空白、HTML)
namespace App\Services\Payment;
use App\Models\Order;
use App\Exceptions\PaymentFailedException;
use function App\Helpers\format_price;
use const App\Config\CURRENCY;
// 類別定義
class Gateway {
public function charge(Order $order): bool { /* ... */ }
}
| 形式 | 語法 | 解析規則 | 範例 (當前 ns: App\Services) |
|---|---|---|---|
| 非限定名稱 | ClassName | 當前命名空間 + 名稱 | new User() → App\Services\User |
| 限定名稱 | Sub\ClassName | 當前命名空間 + 相對路徑 | new Models\User() → App\Services\Models\User |
| 完全限定名稱 | \Top\ClassName | 全域絕對路徑 (前導 \ 表示全域) | new \App\Models\User() → App\Models\User |
<?php
namespace App\Controllers;
use App\Models\User; // 導入類別
use App\Models\Order as OrderModel; // 別名 (避免衝突)
use App\Services\{Payment, Shipping}; // 群組導入 (PHP 7+)
use function App\Helpers\{url, asset}; // 導入函式
use const App\Config\{DEBUG, API_KEY}; // 導入常數
// 動態類別名稱需用完全限定名稱
$class = 'App\Models\User';
$user = new $class(); // 正確
// $user = new User(); // 錯誤:非限定名稱解析為 App\Controllers\User
src/
├── App/
│ ├── Controllers/
│ │ └── UserController.php // namespace App\Controllers;
│ ├── Models/
│ │ └── User.php // namespace App\Models;
│ └── Services/
│ └── Payment/
│ └── Gateway.php // namespace App\Services\Payment;
{
"autoload": {
"psr-4": {
"App\\": "src/App/"
},
"files": ["src/App/Helpers/functions.php"] // 全域函式檔
}
}
執行 composer dump-autoload 產生 vendor/autoload.php,專案入口 require_once __DIR__.'/vendor/autoload.php'; 即可全自動載入。
<?php
namespace App\Services;
class Factory {
public static function make(string $service): object {
$class = __NAMESPACE__ . '\\' . $service; // App\Services\Payment
if (!class_exists($class)) throw new \Exception("Service not found: $class");
return new $class();
}
}
// __NAMESPACE__ 魔術常數:當前命名空間字串
echo __NAMESPACE__; // "App\Services"
// namespace 關鍵字:當前命名空間上下文
$obj = new namespace\Payment\Gateway(); // 相當於 new \App\Services\Payment\Gateway()
<?php
namespace App;
use App\Services\Payment;
// ❌ 錯誤:字串被視為非限定/完全限定,不會套用 use 導入
$class = 'Payment\Gateway';
new $class(); // 尋找 App\Payment\Gateway (不存在)
// ✅ 正確:手動拼接完全限定名稱
$class = 'App\Services\Payment\Gateway';
new $class();
// ✅ 或使用 ::class 常數 (編譯期解析,重構安全)
$class = Payment\Gateway::class; // "App\Services\Payment\Gateway"
new $class();
App\
├── Domain\
│ ├── Entity\ # 實體 (User, Order)
│ ├── ValueObject\ # 值物件 (Money, Email)
│ ├── Repository\ # 儲存庫介面 (UserRepositoryInterface)
│ └── Event\ # 領域事件 (OrderPlaced)
├── Application\
│ ├── Command\ # 命令 (PlaceOrderCommand)
│ ├── Query\ # 查詢 (GetOrderQuery)
│ └── Handler\ # 處理器
├── Infrastructure\
│ ├── Persistence\ # 實作 (EloquentUserRepository)
│ ├── External\ # 第三方整合 (StripeGateway)
│ └── Queue\ # 任務佇列
└── Interface\
├── Http\ # Controller, Request, Resource
├── Console\ # Artisan 命令
└── GraphQL\ # Schema, Resolver
UserRepositoryInterface 或 UserRepository (介面優先)。EloquentUserRepository、DoctrineUserRepository、InMemoryUserRepository (測試用)。$app->bind(UserRepository::class, EloquentUserRepository::class);App\Module\SubModule\Component\Class → 難以記憶、導入冗長。扁平化模組設計。
| 錯誤 | 原因 | 解決 |
|---|---|---|
| Class "User" not found | 未導入、命名空間錯誤、自動載入未生效 | 檢查 use、composer dump-autoload、目錄對應 |
| Cannot use "App\Models\User" as "User" because the name is already in use | 同命名空間下類別與導入別名衝突 | 改用別名 use App\Models\User as UserModel |
| Namespace declaration statement has to be the very first statement | namespace 前有輸出/空白/HTML/註解 | 移至檔案最開頭 ( |
| Function/Const not found in namespace | 函式/常數需額外 use function/use const | PHP 7+ 支援群組導入 use function Ns\{fn1, fn2} |
命名空間是現代 PHP 專案**模組化、自動載入、依賴管理**的基石。遵循 **PSR-4**、**use 導入而非 require**、**完全限定名稱動態調用**、**DDD 分層架構**、**介面與實作分離**,配合 Composer 自動載入、IDE 靜態分析、靜態分析工具 (PHPStan/Psalm),即可構建清晰、可擴充、無命名衝突的企業級 PHP 應用。