我想问一下,我的代码有什么问题。
情况是我想从一个config.json文件中读取一些数据,并且我必须在一个类中使用它。我的想法是使用构造函数,但是脚本不会对值做任何事情。
我的代码:
<?php
class test
{
private $json;
private $config;
private $xmlFiles;
private $modifiedElement;
private $modifiedElement2;
private $exchangeValue;
private $exchangeValue2;
private $inputFolderPath;
private $outputFolderPath;
private $outputFileName;
public function __construct()
{
$this->setXmlFiles();
$this->createFolder();
$this->json = file_get_contents('config.json');
$this->config = json_decode($json,true);
$this->xmlFiles = array();
$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->outputFileName = null;
}在我的config.json上有一些测试数据:
{
"modifiedElement1" : "11",
"modifiedElement2" : "22",
"exchangeValue1" : "11",
"exchangeValue2" : "333",
"inputFolderPath" : "input/",
"outputFolderPath" : "output/"
}你能帮我做这个吗?我试图将变量声明为公共变量,而不是私有变量,但不幸的是,它并没有起作用。
发布于 2022-08-24 12:10:16
代码有几个级别相当低的问题:
$json。您需要使用$this->json,因为这是分配从文件中读取的JSON数据的地方。这应该会在您的代码中生成至少一个警告,但是您没有提到它--确保您总是打开PHP错误报告以进行调试。true参数使它返回一个关联数组,而不是一个对象。因此,稍后尝试访问它的代码(如果它是一个对象)应该会生成一些警告/错误--但前提是您必须首先解码一个实际存在的变量!相反,您需要使用没有json_decode的true argument...and总是阅读手册!变化
$this->config = json_decode($json,true);至
$this->config = json_decode($this->json);为了解决这两个问题。
https://stackoverflow.com/questions/73472746
复制相似问题