我目前正在嘗試使用json_decode填充數據的二維數組。但是,它似乎加載正確,但是當我嘗試獲取特定值時,即使它不是,它也會返回null。二維數組返回null與特定值
我2dtestarray.php:
<?php
class testarray {
public static $listConfigs;
public function __construct() {
$this->listConfigs = json_decode(file_get_contents('configuration.json'), true);
}
public static function getValue($list, $property) {
return self::$listConfigs[$list][$property];
}
public function save() {
file_put_contents('configuration.json',json_encode($listConfigs));
}
}
?>
我testload.php:
<?php
require_once("2darraytest.php");
$ta = new testarray();
var_dump($ta->getValue('main', 'canView'));
var_dump($ta->listConfigs);
$test = json_decode(file_get_contents('configuration.json'), true);
var_dump($test);
$mainList = $test['main']['canView'];
echo $mainList;
?>
我configuration.json:
{"main":{"canView":"true"},"secondary":{"canView":"false"}}
從testload.php輸出:
NULL
array(2) { ["main"]=> array(1) { ["canView"]=> string(4) "true" } ["secondary"]=> array(1) { ["canView"]=> string(5) "false" } }
array(2) { ["main"]=> array(1) { ["canView"]=> string(4) "true" } ["secondary"]=> array(1) { ["canView"]=> string(5) "false" } }
true
最後,我的問題,這就是爲什麼「var_dump($ ta-> getValue('main','canView'));」返回null並且不是真的像「$ mainList = $ test ['main'] ['canView']; echo $ mainList;」呢?
您正在訪問getValue中的靜態屬性,但訪問'$ ta-> listConfigs'中的實例屬性。構造函數將該值設置爲實例屬性。 – andho