简体   繁体   English

PHP数组转换为JSON:尝试获取非对象错误的属性

[英]PHP Array to JSON: Trying to get property of a non-object error

I'm getting "trying to get a property of a non-object" when I'm trying to get values from an array I converted to JSON. 当我尝试从转换为JSON的数组中获取值时,我正在“尝试获取非对象的属性”。

Snippet of Utils.php : Utils.php片段:

class Utils {

    public $config;

    public function __construct($config) {
        $this->config = json_decode(json_encode($config));
    }

Snippet of System.php : 的片段System.php

require_once("Utils.php");
class System extends Utils {
// a bunch of functions
public function bind($port) {
// stuff
$this->writeOutput("Host: {$this->config->MySQL->Host}");

Snippet of Game.php : Game.php片段:

require_once("Config.php");
$utils = new Utils($config);

What Config.php is a bit like: Config.php有点像:

$config = array(

"array" => array(
    "Key" => "Value", 
    "Key2" => "Value"
),

"anotherarray" => array(
    "AnotherKey" => "AnotherValue", 
    "ItsAnArray" => array("key" => "value"),
),

);

It's saying the errors are with every use of $this->config in System.php. 就是说错误与System.php中$ this-> config的每次使用有关。 What am I doing wrong? 我究竟做错了什么?

You can convert the $config parameter in constructor by using 您可以使用以下方法在构造函数中转换$ config参数

public function __construct($config) {
    $this->config = (object) $config;
}

But, remember: converting array into a object is not recursively. 但是请记住:将数组转换为对象不是递归的。 So, you'll have to access the property using this: 因此,您必须使用以下方法访问属性:

$util = new Util($config);

print_r($util->config->array['key']);

As the question still in the same error, try using this: 由于问题仍然存在于同一错误中,请尝试使用此命令:

require_once("Utils.php");
class System extends Utils {

   public function __construct($config){
      parent::__construct($config);
   }

   // a bunch of functions
   public function bind($port) {
      // stuff
      $this->writeOutput("Host: {$this->config->MySQL->Host}");
   }
}

$v = new System($array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM