首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用PHP读取config.json文件

用PHP读取config.json文件
EN

Stack Overflow用户
提问于 2022-08-24 11:58:39
回答 1查看 63关注 0票数 0

我想问一下,我的代码有什么问题。

情况是我想从一个config.json文件中读取一些数据,并且我必须在一个类中使用它。我的想法是使用构造函数,但是脚本不会对值做任何事情。

我的代码:

代码语言:javascript
复制
<?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上有一些测试数据:

代码语言:javascript
复制
{
  "modifiedElement1" : "11", 
  "modifiedElement2" : "22",
  "exchangeValue1" : "11",
  "exchangeValue2" : "333",
  "inputFolderPath" : "input/",
  "outputFolderPath" : "output/"
}

你能帮我做这个吗?我试图将变量声明为公共变量,而不是私有变量,但不幸的是,它并没有起作用。

EN

回答 1

Stack Overflow用户

发布于 2022-08-24 12:10:16

代码有几个级别相当低的问题:

  1. 未定义$json。您需要使用$this->json,因为这是分配从文件中读取的JSON数据的地方。这应该会在您的代码中生成至少一个警告,但是您没有提到它--确保您总是打开PHP错误报告以进行调试。
  2. 根据文档,传递给json_decode的true参数使它返回一个关联数组,而不是一个对象。因此,稍后尝试访问它的代码(如果它是一个对象)应该会生成一些警告/错误--但前提是您必须首先解码一个实际存在的变量!相反,您需要使用没有json_decodetrue argument...and总是阅读手册!

变化

代码语言:javascript
复制
$this->config = json_decode($json,true);

代码语言:javascript
复制
$this->config = json_decode($this->json);

为了解决这两个问题。

现场演示:https://3v4l.org/cfBos

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73472746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档