隨著 PHP 5.3 引入命名空間,大型專案的類別組織、避免命名衝突、自動載入標準化成為可能。本文系統梳理 namespace 宣告、use 導入、別名、動態調用等核心語法,並給出實戰建議。
<?php
// 檔案頂部第一行宣告(除 declare 外)
namespace App\Models\User;
// 或分層
namespace App\Controllers\Admin;
// 同一檔案多命名空間(不推薦,僅演示語法)
namespace Foo { class A {} }
namespace Bar { class B {} }
規則: 一個檔案建議只定義一個命名空間,檔案路徑對應命名空間層級(PSR-4)。
| 方式 | 語法 | 說明 |
|---|---|---|
| 非限定名稱 | User::find(1) | 相對於當前命名空間,若當前為 App\Models 則解析為 App\Models\User |
| 限定名稱 | Models\User::find(1) | 相對於當前命名空間,若當前為 App 則解析為 App\Models\User |
| 完全限定名稱 | \App\Models\User::find(1) | 以 \ 開頭,全域唯一,不受當前命名空間影響 |
<?php
namespace App\Controllers;
use App\Models\User; // 導入類別,後續可直接用 User
use App\Models\Order as OrderModel; // 別名,避免衝突
use function App\Helpers\formatDate; // 導入函數 (PHP 5.6+)
use const App\Config\MAX_SIZE; // 導入常數 (PHP 5.6+)
// 群組導入 (PHP 7+)
use App\Models\{User, Order, Product as P};
<?php
namespace UserCenter;
function check_username() { echo "login OK
"; }
class Login {
public function save() { echo "login saved
"; }
}
<?php
namespace UserCenter\Regist;
function check_username() { echo "regist OK
"; }
class Regist {
public function save() { echo "regist saved
"; }
}
<?php require "login.class.php"; require "regist.class.php"; use UserCenter\Regist; use UserCenter\Regist as Reg; echo \UserCenter\check_username(); // 完全限定 $login = new \UserCenter\Login(); $login->save(); echo Regist\check_username(); // 限定名稱 echo Reg\check_username(); // 別名 $regist = new Reg\Regist(); $regist->save();
composer.json 設定 "App\\": "src/",類別檔案路徑自動對應命名空間,免 require。$class = "\\App\\Models\\$modelName"; $obj = new $class(); 需用完全限定名稱字串。new class() extends \Some\Base {} 同樣受命名空間隔離。Vendor\Project)。use 僅在編譯時建立別名,不會觸發自動載入,實際使用時才會觸發。.. 向上層級,只能用完全限定名稱或 use 導入上層類別。