PHP 使用引用計數為基礎的垃圾回收機制,PHP 5.3 引入演算法解決循環引用問題。本文深度解析 zval 結構、引用計數、循環檢測算法、性能調優與常見內存洩漏場景。
struct _zval_struct {
zvalue_value value; // 實際值(聯合體:long, double, str, arr, obj, res, ref)
zend_uint refcount__gc; // 引用計數器
zend_uchar type; // 類型:IS_STRING, IS_ARRAY, IS_OBJECT...
zend_uchar is_ref__gc; // 是否為引用(& 符號)
};
$b = $a → refcount++(寫時複製 COW)$b = &$a → refcount++、is_ref=1<?php
// 需安裝 xdebug
$a = 'hello';
xdebug_debug_zval('a');
// a: (refcount=1, is_ref=0)='hello'
$b = $a;
xdebug_debug_zval('a');
// a: (refcount=2, is_ref=0)='hello' (COW,共享值)
$c = &$a;
xdebug_debug_zval('a');
// a: (refcount=3, is_ref=1)='hello' (硬引用)
unset($b);
xdebug_debug_zval('a');
// a: (refcount=2, is_ref=1)='hello'
?>
<?php
$arr = ['a' => 'foo', 'b' => 'bar'];
xdebug_debug_zval('arr');
/*
arr: (refcount=1, is_ref=0)=array (
'a' => (refcount=1, is_ref=0)='foo',
'b' => (refcount=1, is_ref=0)='bar'
)
*/
$arr['c'] = $arr['a']; // 同一個字符串 zval
xdebug_debug_zval('arr');
/*
arr: (refcount=1, is_ref=0)=array (
'a' => (refcount=2, is_ref=0)='foo',
'b' => (refcount=1, is_ref=0)='bar',
'c' => (refcount=2, is_ref=0)='foo' // 共享同一 zval
)
*/
?>
<?php
class A {}
$obj = new A();
xdebug_debug_zval('obj');
// obj: (refcount=1, is_ref=0)=object(A)#1 (0) {}
// 對象賦值複製的是句柄(handle),指向同一對象
$obj2 = $obj;
xdebug_debug_zval('obj');
// obj: (refcount=2, is_ref=0)=object(A)#1 (0) {}
// 修改屬性影響同一對象
$obj->prop = 'value';
echo $obj2->prop; // 'value'
?>
<?php
class Node {
public ?Node $parent = null;
public ?Node $child = null;
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
}
$parent = new Node('parent');
$child = new Node('child');
$parent->child = $child;
$child->parent = $parent; // 循環引用!
unset($parent, $child);
// PHP 5.2:內存洩漏,refcount 永遠 > 0,析構函數不調用
// PHP 5.3+:GC 會檢測並回收
?>
gc_collect_cycles()gc_enable() 開啟時(默認開啟)<?php
class EventDispatcher {
private array $listeners = [];
public function listen(string $event, callable $listener): void {
$this->listeners[$event][] = $listener;
}
// 缺少 unlisten() 導致監聽者無法釋放
}
class UserService {
public function __construct(private EventDispatcher $dispatcher) {
$this->dispatcher->listen('user.created', [$this, 'onUserCreated']);
}
public function onUserCreated(User $user): void {
// ...
}
// 銷毀時未移除監聽器 → 循環引用
}
// 修正:實現清理接口
interface Disposable {
public function dispose(): void;
}
class UserService implements Disposable {
// ...
public function dispose(): void {
// 需手動調用或框架自動調用
}
}
?>
<?php
class Service {
public \Closure $callback;
public function __construct() {
// 閉包捕獲 $this → 循環引用
$this->callback = function() {
$this->doSomething(); // 隱式捕獲 $this
};
}
// PHP 8.1+ 可用 readonly 避免意外修改
// 解決:使用弱引用 WeakReference
public function setCallback(\Closure $cb): void {
$this->callback = $cb;
}
}
// 正確:弱引用不增加 refcount
$service = new Service();
$weakRef = WeakReference::create($service);
$service->callback = function() use ($weakRef) {
if ($svc = $weakRef->get()) {
$svc->doSomething();
}
};
?>
<?php
class Cache {
private static array $instances = []; // 靜態屬性持有引用
public static function getInstance(string $key): self {
return self::$instances[$key] ??= new self($key);
}
// 永不釋放,除非手動清理
public static function clear(): void {
self::$instances = [];
}
}
// 長運行腳本必須定期清理
// register_shutdown_function([Cache::class, 'clear']);
?>
; 開啟/關閉 GC(默認 On)
zend.enable_gc = On
; GC 根緩衝區大小(默認 10000)
; 增大可減少 GC 頻率,但增加內存佔用
; gc.collect_cycles() 手動觸發不受此限制
; 此設置需在編譯時配置:--enable-gc 指定大小,運行時不可修改
; 內存限制
memory_limit = 256M
<?php
// 開啟/關閉 GC
gc_enable();
gc_disable();
// 手動觸發循環回收,返回回收數量
$collected = gc_collect_cycles();
echo "回收了 $collected 個循環引用\n";
// 獲取 GC 狀態
$status = gc_status();
// [
// 'runs' => 5, // GC 運行次數
// 'collected' => 1234, // 總回收數
// 'threshold' => 10000, // 閾值
// 'roots' => 123, // 當前根節點數
// ]
?>
<?php
// 策略 1:定期手動觸發(如每 1000 次迭代)
for ($i = 0; $i < 100000; $i++) {
processItem($i);
if ($i % 1000 === 0) {
gc_collect_cycles(); // 主動回收,避免內存尖峰
}
}
// 策略 2:關閉 GC,僅在安全點手動觸發
gc_disable();
foreach ($largeDataset as $item) {
process($item);
if (memory_get_usage() > 200 * 1024 * 1024) { // 200MB
gc_collect_cycles();
}
}
gc_enable();
// 策略 3:分批處理,讓腳本結束自然釋放
function processInBatches(iterable $data, int $batchSize = 1000): Generator {
$batch = [];
foreach ($data as $item) {
$batch[] = $item;
if (count($batch) >= $batchSize) {
yield $batch;
$batch = [];
// 此處 GC 可回收上一批次
}
}
if ($batch) yield $batch;
}
?>
<?php
// 實時內存使用
echo "當前內存:" . formatBytes(memory_get_usage(true)) . "\n"; // 含 PHP 分配
echo "峰值內存:" . formatBytes(memory_get_peak_usage(true)) . "\n";
// Xdebug 追蹤內存分配
// xdebug.start_with_request=trigger
// XDEBUG_TRIGGER=profile php script.php
// 生產環境監控
function logMemoryUsage(string $checkpoint): void {
$usage = memory_get_usage(true);
$peak = memory_get_peak_usage(true);
error_log("[$checkpoint] Memory: " . formatBytes($usage) . " Peak: " . formatBytes($peak));
}
logMemoryUsage('start');
$data = loadLargeDataset();
logMemoryUsage('after_load');
process($data);
logMemoryUsage('after_process');
unset($data);
gc_collect_cycles();
logMemoryUsage('after_cleanup');
?>
$a = $b 是 COW,$a = &$b 是硬引用dispose()、閉包用 WeakReferencegc_collect_cycles()、分批處理、監控內存yield 流式處理,避免全量載入__destruct() 僅做資源清理,不依賴其執行時機memory_get_usage(true) 監控真實分配內存zend.enable_gc=On,必要時調整閾值