2017-04-18 186 views
0

我有一个文件用作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" 
    ) 
); 

在我的班级我有一个构造函数调用此: 私人$配置;

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

在你的例子中只有$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)); 
+0

有什么stdClass的东西? –

+0

这就是对象。无论何时通过强制转型创建对象,或者通过未指定类的源创建对象,它都属于'stdClass'类。 – AbraCadaver

相关问题