Php 试图从返回的对象获取非对象的属性
我有一个用作PHP的文件,作为配置文件来存储可能需要频繁更改的信息。我将数组作为对象返回,如下所示:Php 试图从返回的对象获取非对象的属性,php,object,Php,Object,我有一个用作PHP的文件,作为配置文件来存储可能需要频繁更改的信息。我将数组作为对象返回,如下所示: return (object) array( "host" => array( "URL" => "https://thomas-smyth.co.uk" ), "dbconfig" => array( "DBHost" => "localhost", "DBPort" => "3306",
return (object) array(
"host" => array(
"URL" => "https://thomas-smyth.co.uk"
),
"dbconfig" => array(
"DBHost" => "localhost",
"DBPort" => "3306",
"DBUser" => "thomassm_sqlogin",
"DBPassword" => "SQLLoginPassword1234",
"DBName" => "thomassm_CadetPortal"
),
"reCaptcha" => array(
"reCaptchaURL" => "https://www.google.com/recaptcha/api/siteverify",
"reCaptchaSecretKey" => "IWouldNotBeSecretIfIPostedItHere"
)
);
在我的类中,我有一个构造函数来调用:
私有$config
function __construct(){
$this->config = require('core.config.php');
}
以及如何使用它:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => $this->config->reCaptcha->reCaptchaSecretKey, 'response' => $StrToken)));
但是,我得到了一个错误:
[18-Apr-2017 21:18:02 UTC] PHP Notice: Trying to get property of non-object in /home/thomassm/public_html/php/lib/CoreFunctions.php on line 21
我不明白为什么会发生这种情况,因为它是作为一个对象返回的,而且它似乎对其他人有效,因为我是从另一个问题中得到这个想法的。有什么建议吗?在您的示例中,只有
$this->config
是一个对象。属性是数组,因此您可以使用:
$this->config->reCaptcha['reCaptchaSecretKey']
该对象如下所示:
stdClass Object
(
[host] => Array
(
[URL] => https://thomas-smyth.co.uk
)
[dbconfig] => Array
(
[DBHost] => localhost
[DBPort] => 3306
[DBUser] => thomassm_sqlogin
[DBPassword] => SQLLoginPassword1234
[DBName] => thomassm_CadetPortal
)
[reCaptcha] => Array
(
[reCaptchaURL] => https://www.google.com/recaptcha/api/siteverify
[reCaptchaSecretKey] => IWouldNotBeSecretIfIPostedItHere
)
)
要使所有对象都可以JSON编码然后解码:
$this->config = json_decode(json_encode($this->config));
什么是stdClass?那是对象。无论何时通过强制转换或从未指定类的源创建对象,它都属于
stdClass
类。