PHP读取config.json时构造函数无法获取配置值问题求助
问题分析与修复方案
你的代码存在三个核心问题,导致无法正确读取config.json的配置值:
1. 未正确引用类属性
在json_decode时,你直接使用了$json,但这个变量是类的私有属性,必须通过$this->json来访问:
// 错误写法 $this->config = json_decode($json,true); // 正确写法 $this->config = json_decode($this->json,true);
2. 混淆了数组与对象的访问方式
json_decode的第二个参数设为true时,返回的是关联数组,不是对象,因此不能用->来访问属性,必须改用数组下标语法:
// 错误写法 $this->modifiedElement = $this->config->modifiedElement1; // 正确写法 $this->modifiedElement = $this->config['modifiedElement1'];
所有通过$this->config访问配置的行都需要改成数组下标形式。
3. 方法调用顺序错误
你在构造函数开头先调用了setXmlFiles()和createFolder(),但此时配置还未加载,这两个方法如果依赖配置值的话,会因为变量未初始化而报错。应该先加载配置,再调用这些方法:
public function __construct() { // 先加载配置 $this->json = file_get_contents('config.json'); $this->config = json_decode($this->json,true); // 初始化配置相关属性 $this->modifiedElement = $this->config['modifiedElement1']; $this->modifiedElement2 = $this->config['modifiedElement2']; $this->exchangeValue = $this->config['exchangeValue1']; $this->exchangeValue2 = $this->config['exchangeValue2']; $this->inputFolderPath = $this->config['inputFolderPath']; $this->outputFolderPath = $this->config['outputFolderPath']; $this->xmlFiles = array(); $this->outputFileName = null; // 再调用依赖配置的方法 $this->setXmlFiles(); $this->createFolder(); }
额外建议
- 可以在
file_get_contents后增加错误判断,避免文件不存在或读取失败导致后续逻辑崩溃:
$this->json = file_get_contents('config.json'); if (!$this->json) { throw new Exception('无法读取config.json文件'); }
- 也可以去掉
$json属性,直接链式调用简化代码:
$this->config = json_decode(file_get_contents('config.json'), true);
内容的提问来源于stack exchange,提问作者smate
相关产品推荐
相关产品推荐

