
本文详解php操作json文件时因误将函数名当作变量调用(如$json_encode())导致的致命错误,提供完整修复方案、安全编码实践及常见陷阱规避方法。
本文详解php操作json文件时因误将函数名当作变量调用(如$json_encode())导致的致命错误,提供完整修复方案、安全编码实践及常见陷阱规避方法。
在PHP中动态读写JSON文件是构建轻量级数据存储应用的常见需求,但初学者极易因语法混淆引发严重运行时错误。你遇到的报错:
Warning: Undefined variable $json_encode in .../newtodo.php on line 16 Fatal error: Uncaught Error: Value of type NULL is not callable ...
根本原因在于这一行代码存在函数调用语法错误:
file_put_contents('todo.json', $json_encode($jsonArray, JSON_PRETTY_PRINT)); // ❌ 错误:$json_encode 是变量(未定义),不是函数
PHP中JSON编码函数名为 json_encode()(无美元符 $),而 $json_encode 被解释为一个变量——该变量从未声明,值为 null,因此 PHP 尝试调用 null() 导致“Value of type null is not callable”致命错误。
✅ 正确写法应为:
立即学习“PHP免费学习笔记(深入)”;
file_put_contents('todo.json', json_encode($jsonArray, JSON_PRETTY_PRINT)); // ✅ 正确:调用内置函数 json_encode()
完整修复后的健壮代码示例
以下为推荐的生产就绪写法,已加入错误处理、空值防护与JSON验证:
<?php $todoname = $_POST['todoname'] ?? ''; $todoname = trim($todoname); if (!empty($todoname)) { // 1. 安全读取JSON文件 $jsonFile = 'todo.json'; if (!file_exists($jsonFile)) { // 初始化空JSON对象(避免首次运行失败) $jsonArray = []; } else { $jsonContent = file_get_contents($jsonFile); if ($jsonContent === false) { die("Error: Failed to read $jsonFile"); } $jsonArray = json_decode($jsonContent, true); if (json_last_error() !== JSON_ERROR_NONE) { die("Error: Invalid JSON in $jsonFile"); } } // 2. 添加新待办项(使用唯一键或追加数组,避免键名冲突) $jsonArray[] = [ 'name' => $todoname, 'completed' => false, 'created_at' => date('c') ]; // 3. 安全写入:先编码,再写入,检查结果 $encoded = json_encode($jsonArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); if ($encoded === false) { die("Error: Failed to encode JSON — " . json_last_error_msg()); } if (file_put_contents($jsonFile, $encoded) === false) { die("Error: Failed to write to $jsonFile"); } echo "✅ Todo added successfully!"; } ?>
关键注意事项
- 命名规范:PHP内置函数一律无 $ 前缀(如 json_encode, json_decode, file_get_contents),变量才以 $ 开头(如 $jsonArray);
- JSON结构建议:避免使用用户输入作为数组键(如 $jsonArray[$todoname]),易引发键名冲突或非法字符问题;推荐使用索引数组或UUID生成唯一ID;
- 文件权限:确保Web服务器对 todo.json 有写权限(如 chmod 644 todo.json,必要时设为 664);
- 并发安全:高并发场景下,file_get_contents + file_put_contents 非原子操作,应考虑加锁(如 flock())或改用数据库;
- UTF-8支持:添加 JSON_UNESCAPED_UNICODE 标志,避免中文被转义为 uXXXX。
通过修正函数调用语法并引入基础防御性编程,即可彻底解决该错误,并为后续功能扩展打下可靠基础。