I would like to ask what could be the problem with my code.
The situation is that I would like to read some data from a config.json file, and I have to use it in a class. My idea is to use a constructor function, but the script does not do anything with the values.
My code:
<?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;
}
On my config.json there are some test data:
{
"modifiedElement1" : "11",
"modifiedElement2" : "22",
"exchangeValue1" : "11",
"exchangeValue2" : "333",
"inputFolderPath" : "input/",
"outputFolderPath" : "output/"
}
Can you help me with this? I tried to declare the variables as public instead of private, did not work anyway unfortunately.
The code has a couple of fairly low-level issues:
$jsonis not defined. You need to use$this->jsonsince that's where you assigned the JSON data you read in from the file. This should be generating at least one warning in your code, but you didn't mention it - make sure you always have PHP error reporting switched on for debugging.As per the documentation, the
trueargument you've passed to json_decode makes it returns an associative array instead of an object. Therefore the code later on trying to access it as if it's an object should generate some warnings/errors - but only if you first decode a variable which actually exists! Instead, you need to usejson_decodewithout thetrueargument...and always read the manual!Change
to
in order to resolve those two issues.
Live demo: https://3v4l.org/cfBos