PHP 採用函數級作用域:函數內部預設無法直接訪問外部變數。global 關鍵字與 $GLOBALS 超全域陣列是打破這層隔離的兩種機制,本文深度解析其原理、差異與現代替代方案。
<?php
$pangbu = "pangbu";
function demo() {
global $pangbu; // 在函數內建立 $pangbu 別名,指向全域 $pangbu
echo $pangbu; // pangbu
}
demo();
?>
<?php
// global $var 等價於:
$var = &$GLOBALS['var']; // 建立引用別名
// 驗證:修改別名影響原變數
$x = 1;
function test() {
global $x;
$x = 2;
}
test();
echo $x; // 2,全域變數被修改
?>
<?php
// ❌ 語法錯誤:Parse error
global $url = "www.example.com";
// ✅ 正確:先宣告,再賦值
global $url;
$url = "www.example.com";
?>
<?php
$url = "www.111cn.net";
function get_url() {
// 直接訪問,無需 global 宣告
echo "The blog url is " . $GLOBALS['url'];
}
get_url(); // The blog url is www.111cn.net
?>
| 維度 | global $var | $GLOBALS['var'] |
|---|---|---|
| 機制 | 建立區域別名引用 | 直接操作全域符號表 |
| 作用域 | 僅當前函數內有效 | 任何位置可用 |
| 變數存在性 | 若全域不存在,創建 NULL 別名 | 若不存在,訪問觸發 Notice |
| 動態變數名 | 不支援 | 支援 $GLOBALS[$dynamicName] |
| 效能 | 微小別名開銷 | 直接陣列訪問,略快 |
| 可讀性 | 語義清晰「聲明使用全域」 | 顯式但較冗長 |
<?php
$a = 1; // 全域作用域
include 'b.inc'; // include 不創建新作用域,$a 可見
function testScope() {
// 區域作用域開始
$a = 10; // 區域變數,遮蔽全域 $a
echo "區域 \$a: $a<br>"; // 10
global $a; // 切換到全域別名
echo "全域 \$a: $a<br>"; // 1
$GLOBALS['a'] = 100; // 直接修改全域
}
testScope();
echo "全域 \$a 最終: $a<br>"; // 100
?>
PHP 內建超全域陣列(自動全域,無需 global):
$GLOBALS:所有全域變數$_SERVER:伺服器/執行環境資訊$_GET、$_POST、$_REQUEST:輸入資料$_SESSION:會話資料$_COOKIE:Cookie 資料$_FILES:上傳檔案$_ENV:環境變數<?php
function testSuperglobals() {
// 普通全域變數需要 global
global $customVar;
// 超全域直接可用
echo $_POST['name'] ?? 'no post';
echo $_SERVER['REQUEST_METHOD'];
// $GLOBALS 也是超全域
echo $GLOBALS['customVar'];
}
?>
<?php
function counter() {
static $count = 0; // 僅初始化一次
$count++;
echo "Call $count<br>";
}
counter(); // 1
counter(); // 2
counter(); // 3
// 遞歸中的靜態變數
function recursive($n) {
static $depth = 0;
$depth++;
if ($depth > 10) return;
recursive($n);
$depth--;
}
?>
<?php
function foo() {
static $int = 0; // ✅ 正確:常量
static $int = 1 + 2; // ❌ 錯誤:運算式(PHP 5.6+ 支援常量運算式)
static $int = sqrt(121); // ❌ 錯誤:函數調用
}
?>
<?php
// ❌ 依賴全域
function getUser($id) {
global $pdo;
return $pdo->query("SELECT * FROM users WHERE id=$id")->fetch();
}
// ✅ 依賴注入:透明、可測試、可替換
class UserRepository {
public function __construct(private PDO $pdo) {}
public function findById(int $id): ?array {
$stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch() ?: null;
}
}
// 使用
$repo = new UserRepository($pdo);
$user = $repo->findById(1);
// 測試時輕鬆 Mock
$mockPdo = new class extends PDO { /* ... */ };
$testRepo = new UserRepository($mockPdo);
?>
<?php
class Container {
private array $services = [];
public function set(string $id, callable $factory): void {
$this->services[$id] = $factory;
}
public function get(string $id) {
if (!isset($this->services[$id])) {
throw new Exception("Service $id not found");
}
$factory = $this->services[$id];
return $factory($this); // 傳入容器支援自動裝配
}
}
$container = new Container();
$container->set('pdo', fn() => new PDO(...));
$container->set('user_repo', fn($c) => new UserRepository($c->get('pdo')));
// 獲取服務(單例模式可在工廠內實現)
$userRepo = $container->get('user_repo');
?>
global、$GLOBALS 使用點Config、Database)global 建立區域別名引用全域變數,$GLOBALS 直接操作全域符號表global $x ≡ $x = &$GLOBALS['x']