PHP 沒有名為 delete() 的函數。刪除檔案請用 unlink(),刪除變數請用 unset()。本文詳細說明兩者語法、行為差異、常見陷阱與實戰範例。
unlink(string $filename, resource $context = null): bool
true,失敗回傳 false (權限不足、檔案不存在、被鎖定)。<?php
$file = '/tmp/cache/data.json';
if (file_exists($file)) {
if (unlink($file)) {
echo "刪除成功";
} else {
echo "刪除失敗,檢查權限";
}
} else {
echo "檔案不存在";
}
// 批次刪除目錄下所有 .tmp 檔
$files = glob('/tmp/*.tmp');
foreach ($files as $f) {
@unlink($f); // 抑制單一失敗警告
}
?>
unset(mixed $var, mixed ...$vars): void
unset 僅銷毀區域引用,下次呼叫仍保留原值。<?php
$a = 'hello';
$b = &$a; // 參考
unset($a);
echo $b; // hello (參考計數仍為 1)
$arr = [1,2,3];
unset($arr[1]); // 移除索引 1,陣列變 [0=>1, 2=>3] (索引不重排)
// 重排索引用 array_values()
$arr = array_values($arr); // [0=>1, 1=>3]
// 釋放大型陣列記憶體
$big_data = range(1, 1000000);
unset($big_data); // 立即釋放
?>
| 操作 | 函數 | 錯誤用法 | 正確用法 |
|---|---|---|---|
| 刪除檔案 | unlink | delete($file) | unlink($file) |
| 刪除變數 | unset | delete($var) | unset($var) |
| 刪除陣列元素 | unset | $arr = []; (重新賦值) | unset($arr[key]) |
| 清空陣列 | unset | unset($arr) 後無法直接用 | $arr = []; 或 array_splice($arr, 0) |
<?php
class Node {
public $parent = null;
public $children = [];
}
$a = new Node();
$b = new Node();
$a->children[] = $b;
$b->parent = $a; // 循環引用
unset($a, $b); // 計數歸零但未立即釋放
gc_collect_cycles(); // 強制回收循環引用
?>
記住:檔案用 unlink(),變數用 unset()。PHP 無 delete() 函數。掌握兩者作用域、引用計數與陣列索引行為,能避免記憶體洩漏與邏輯錯誤。