Thomas Smyth
Thomas Smyth

Reputation: 522

Trying to get property of non-object from a returned object

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?

Upvotes: 0

Views: 623

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 79024

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

Upvotes: 1

Related Questions