命名空间
namespace 定义、use 导入、自动加载、命名空间解析规则
命名空间
PHP 的命名空间解决了类名冲突问题——同一个项目可以有多个 User 类,各自在自己的命名空间中。
学完本章你将: 掌握 namespace/use、自动加载、命名空间解析。
namespace 基础
php
<?php
// src/Models/User.php
namespace App\Models;
class User {
public function __construct(public string $name) { }
}
// src/Controllers/UserController.php
namespace App\Controllers;
use App\Models\User; // 导入
class UserController {
public function show(int $id): void {
$user = new User("小明"); // 使用导入的类
}
}
use 快捷键
php
<?php
// 别名
use App\Models\User as UserModel;
// 批量导入
use App\Models\{User, Post, Comment};
// 导入函数/常量(PHP 5.6+)
use function App\Helpers\formatDate;
use const App\Config\APP_NAME;
命名空间解析规则
php
<?php
namespace App\Services;
new User(); // App\Services\User(当前命名空间)
new \App\Models\User(); // App\Models\User(绝对路径)
new \DateTime(); // DateTime(系统类,自动查全局)
// ⚠️ 在一个有命名空间的文件中,PHP 内置函数需要加 \ 或导入
// \strlen("hello") 或 use function strlen;