PHP数组到JSON:尝试获取非对象错误的属性
当我试图从转换为JSON的数组中获取值时,我得到了“尝试获取非对象的属性”PHP数组到JSON:尝试获取非对象错误的属性,php,arrays,object,json,Php,Arrays,Object,Json,当我试图从转换为JSON的数组中获取值时,我得到了“尝试获取非对象的属性” Utils.php的片段: class Utils { public $config; public function __construct($config) { $this->config = json_decode(json_encode($config)); } require_once("Utils.php"); class System extends Ut
Utils.php
的片段:
class Utils {
public $config;
public function __construct($config) {
$this->config = json_decode(json_encode($config));
}
require_once("Utils.php");
class System extends Utils {
// a bunch of functions
public function bind($port) {
// stuff
$this->writeOutput("Host: {$this->config->MySQL->Host}");
require_once("Config.php");
$utils = new Utils($config);
System.php的一段代码
:
class Utils {
public $config;
public function __construct($config) {
$this->config = json_decode(json_encode($config));
}
require_once("Utils.php");
class System extends Utils {
// a bunch of functions
public function bind($port) {
// stuff
$this->writeOutput("Host: {$this->config->MySQL->Host}");
require_once("Config.php");
$utils = new Utils($config);
Game.php的片段
:
class Utils {
public $config;
public function __construct($config) {
$this->config = json_decode(json_encode($config));
}
require_once("Utils.php");
class System extends Utils {
// a bunch of functions
public function bind($port) {
// stuff
$this->writeOutput("Host: {$this->config->MySQL->Host}");
require_once("Config.php");
$utils = new Utils($config);
Config.php有点像:
$config = array(
"array" => array(
"Key" => "Value",
"Key2" => "Value"
),
"anotherarray" => array(
"AnotherKey" => "AnotherValue",
"ItsAnArray" => array("key" => "value"),
),
);
它的意思是每次在System.php中使用$this->config时都会出现错误。我做错了什么?您可以使用
public function __construct($config) {
$this->config = (object) $config;
}
但是,请记住:将数组转换为对象不是递归的。因此,您必须使用以下方法访问该属性:
$util = new Util($config);
print_r($util->config->array['key']);
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);
由于问题仍然存在相同的错误,请尝试使用以下方法:
$util = new Util($config);
print_r($util->config->array['key']);
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);
为什么要在同一行中将数组编码/解码为JSON?这是我在上一篇文章中的答案:这是一个很好的编程,对吧?请用行发布完整的错误详细信息。@Will这真的很糟糕。请参阅我在上一个问题中对该答案的评论。至于您的“非对象”问题,您是否在使用时运行
System
object的构造函数?我可以看到你从哪里得到Utils对象的新实例,但不是系统。它仍然说“试图得到一个非对象的属性”。