<?php
$myVar = 'Hello World';
function testGlobal() {
// 函數作用域內無法直接訪問 $myVar
// echo $myVar; // Notice: Undefined variable
// 引入全局變量
global $myVar;
echo $myVar; // Hello World
// 修改全局變量
$myVar = 'Modified';
}
testGlobal();
echo $myVar; // Modified
?>
<?php
// ❌ 依賴全局
function saveUser() {
global $db;
$db->insert('users', $_POST);
}
// ✅ 顯式依賴
function saveUser(PDO $db, array $data): bool {
return $db->insert('users', $data);
}
// 調用
saveUser($pdo, $_POST); // 清晰、可測試、可復用
?>
<?php
// 簡易容器示例
class Container {
private $services = [];
private $factories = [];
public function bind(string $id, callable $factory) {
$this->factories[$id] = $factory;
}
public function get(string $id) {
if (isset($this->services[$id])) return $this->services[$id];
if (!isset($this->factories[$id])) throw new Exception("Service $id not found");
return $this->services[$id] = $this->factories[$id]($this);
}
}
$container = new Container();
$container->bind('db', fn($c) => new PDO('mysql:host=localhost;dbname=test', 'user', 'pass'));
$container->bind('user_repo', fn($c) => new UserRepository($c->get('db')));
// 使用
$userRepo = $container->get('user_repo');
$userRepo->save(['name' => 'John']);
?>
<?php
class Database {
private static ?PDO $instance = null;
public static function getInstance(): PDO {
if (!self::$instance) {
self::$instance = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instance;
}
// 禁止克隆/序列化
private function __clone() {}
public function __wakeup() { throw new Exception('不可序列化'); }
}
// 使用
$db = Database::getInstance();
$stmt = $db->query('SELECT 1');
?>
<?php
// 替代全局配置數組
class AppConfig {
public function __construct(
public readonly string $dbHost,
public readonly string $dbName,
public readonly string $appEnv,
public readonly int $cacheTtl
) {}
}
// 構建一次,到處傳遞
$config = new AppConfig('localhost', 'myapp', 'prod', 3600);
function connect(AppConfig $config): PDO { /* ... */ }
?>
<?php
class RequestContext {
public function __construct(
public array $get,
public array $post,
public array $server,
public array $cookies,
public ?User $user = null
) {}
}
// 中間件創建上下文,控制器接收
function handleRequest(RequestContext $ctx) {
// 完全可測試,無全局依賴
}
?>
$GLOBALS, $_GET, $_POST, $_SESSION) 本質即全局,框架通常封裝為 Request 對象。<?php
$x = 1;
function testGlobal() {
global $x;
$x = 2; // 修改全局 $x
}
function testGlobals() {
$GLOBALS['x'] = 3; // 修改全局 $x
// 區別:$GLOBALS 可用動態變量名
$varName = 'x';
$GLOBALS[$varName] = 4;
}
testGlobal(); // $x = 2
testGlobals(); // $x = 4
?>
global 是 PHP 早期為過程式代碼設計的妥協產物。現代 PHP (5.3+) 應採用依賴注入、服務容器、請求上下文對象等模式,實現顯式依賴、易測試、高復用、低耦合的代碼架構。將全局狀態最小化、局部化、封裝化,是專業 PHP 開發者的核心素養。