2017-04-18 202 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

相關問題