douyi6290 2017-04-18 21:36
浏览 36
已采纳

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

I have a file I am using as a PHP to act as a config file to store info that might need to be changed frequently. I return the array as an object, like so:

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

In my classes I have a constructor to call this: private $config;

function __construct(){
    $this->config = require('core.config.php');
}

And the use it like:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => $this->config->reCaptcha->reCaptchaSecretKey, 'response' => $StrToken)));

However, I am given the error:

[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

I don't understand why this is happening considering the thing is returned as an object and it seemed to work for other people, as I got this idea from another question. Any suggestions?

  • 写回答

1条回答 默认 最新

  • dongtan1845 2017-04-18 21:38
    关注

    In your example only $this->config is an object. The properties are arrays, so you would use:

    $this->config->reCaptcha['reCaptchaSecretKey']
    

    The object looks like this:

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

    To have all objects you could JSON encode and then decode:

    $this->config = json_decode(json_encode($this->config));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路