尝试从返回的对象获取非对象的属性

时间:2017-04-18 21:36:08

标签: php object

我有一个文件,我用作PHP作为配置文件来存储可能需要经常更改的信息。我将数组作为对象返回,如下所示:

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"
    )
);

在我的课程中,我有一个构造函数来调用它:     private $ 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

我不明白为什么会发生这种情况,因为这件事作为一个对象返回,而且它似乎适用于其他人,因为我从另一个问题中得到了这个想法。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

在您的示例中,只有$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));