2D数组返回具有特定值的null

时间:2013-03-31 04:12:38

标签: php json

我正在尝试使用json_decode用数据填充2D数组。但是,它似乎加载正确,但是当我尝试获取特定值时,即使它不是,它也会返回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-&gt; getValue('main','canView'));”返回null而不是像“$ mainList = $ test ['main'] ['canView']; echo $ mainList;”呢?

1 个答案:

答案 0 :(得分:0)

您正在访问getValue中的静态属性:

self::$listConfigs[$list][$property]

但访问$ta->listConfigs中的实例属性。构造函数将值设置为实例属性。

$this->listConfigs = json_decode(file_get_contents('configuration.json'), true);

因此,这会导致实例同时访问静态self::$listConfigs和实例属性$this->listConfigs

尝试更改构造函数以使用静态属性。

public function __construct() {
    self::$listConfigs = json_decode(file_get_contents('configuration.json'), true);
}
相关问题