簡體   English   中英

讀取 PHP 中的 config.json 文件

[英]Reading config.json file in PHP

我想問你我的代碼有什么問題。

情況是我想從 config.json 文件中讀取一些數據,我必須在 class 中使用它。 我的想法是使用構造函數 function,但腳本對這些值沒有任何作用。

我的代碼:

    <?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/"
}

你能幫我解決這個問題嗎? 我試圖將變量聲明為公共而不是私有,不幸的是無論如何都沒有用。

先感謝您!

該代碼有幾個相當低級的問題:

  1. $json未定義。 您需要使用$this->json ,因為這是您分配從文件中讀取的 JSON 數據的位置。 這應該在您的代碼中產生至少一個警告,但您沒有提及它 - 確保您始終打開 PHP 錯誤報告以進行調試。

  2. 根據文檔,您傳遞給 json_decode 的true參數使其返回關聯數組而不是 object。 因此,稍后嘗試像 object 一樣訪問它的代碼應該會產生一些警告/錯誤 - 但前提是您首先解碼實際存在的變量,相反,您需要使用沒有true參數的json_decode ...並且始終閱讀手冊!

改變

$this->config = json_decode($json,true);

$this->config = json_decode($this->json);

為了解決這兩個問題。

現場演示: https://3v4l.org/cfBos

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM