var_dump() 和 var_export() 是 PHP 開發中最常用的兩個變量檢查函數,雖然都能輸出變量結構,但設計目的、輸出格式、適用場景截然不同。本文深度對比兩者差異,並展示 var_export 獨特的「生成可執行 PHP 代碼」能力。
eval/include |
| **返回值** | 無 (void) | 可選返回字串 (bool $return=true) |
| **資源類型** | 顯示 resource(1) of type (stream) | 返回 NULL(不可序列化) |
| **遞歸處理** | 自動遞歸展開,縮進顯示 | 遞歸生成代碼,支援循環引用檢測 |
| **輸出控制** | 需配合 ob_start() 捕獲 | 直接返回字串,無需緩衝區 |
<?php
$a = [1, 2, ['a', 'b', 'c']];
$b = 3.14;
$c = true;
var_dump($a, $b, $c);
/* 輸出:
array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> array(3) {
[0]=> string(1) "a"
[1]=> string(1) "b"
[2]=> string(1) "c"
}
}
float(3.14)
bool(true)
*/
?>
特點:顯示類型(int/string/array/object/resource)、長度、結構縮進,適合開發調試、變量快照。
<?php
$config = [
'app' => [
'name' => 'MyApp',
'debug' => true,
'version' => '1.0.0',
],
'db' => [
'host' => 'localhost',
'port' => 3306,
],
];
// 1. 直接輸出
var_export($config);
/* 輸出:
array (
'app' =>
array (
'name' => 'MyApp',
'debug' => true,
'version' => '1.0.0',
),
'db' =>
array (
'host' => 'localhost',
'port' => 3306,
),
)
*/
// 2. 返回字串(第二參數 true)
$code = '
<?php
class ConfigCache {
private string $cacheFile;
public function __construct(string $cacheFile) {
$this->cacheFile = $cacheFile;
}
public function write(array $config): void {
$code = "cacheFile, $code, LOCK_EX);
}
public function read(): array {
if (!file_exists($this->cacheFile)) return [];
return include $this->cacheFile; // 直接執行返回陣列
}
}
// 使用
$cache = new ConfigCache(__DIR__ . '/cache/config.php');
$cache->write(['debug' => true, 'keys' => ['a'=>1, 'b'=>2]]);
$config = $cache->read();
?>
<?php
$statusMap = [
1 => 'pending',
2 => 'processing',
3 => 'completed',
4 => 'cancelled',
];
$code = '
<?php
$fp = fopen('test.txt', 'r');
var_dump($fp); // resource(5) of type (stream)
var_export($fp); // NULL
// 解決方案:資源轉換為可序列化標識
function exportable($var) {
if (is_resource($var)) {
return ['__resource_type' => get_resource_type($var)];
}
if (is_array($var)) {
return array_map('exportable', $var);
}
return $var;
}
var_export(exportable($fp)); // array('__resource_type' => 'stream')
?>
print_r():輸出可讀格式,print_r($var, true) 返回字串,**不包含類型信息**,無法直接作為代碼執行var_dump():含類型長度,調試首選var_export():輸出合法 PHP 代碼,可 include/eval 還原,適合緩存、導出var_export 生成代碼字串佔用雙倍內存var_dump 或 xdebug.var_display_max_depth 限制深度var_export 配合 opcache 效能極佳(直接編譯為字節碼)var_dump()(或 xdebug 面板)var_export($arr, true)var_dump 可見,var_export 返回 NULL,需自行轉換var_export 會報錯 Nesting level too deep,需預處理打破循環善用 var_export 的「代碼生成」特性,能構建高性能的配置緩存、靜態數據導出、代碼生成器等工程化能力,是從「寫腳本」邁向「工程化 PHP」的關鍵技能之一。