0

I'm getting "trying to get a property of a non-object" when I'm trying to get values from an array I converted to JSON.

Snippet of Utils.php:

class Utils {

    public $config;

    public function __construct($config) {
        $this->config = json_decode(json_encode($config));
    }

Snippet of System.php:

require_once("Utils.php");
class System extends Utils {
// a bunch of functions
public function bind($port) {
// stuff
$this->writeOutput("Host: {$this->config->MySQL->Host}");

Snippet of Game.php:

require_once("Config.php");
$utils = new Utils($config);

What Config.php is a bit like:

$config = array(

"array" => array(
    "Key" => "Value", 
    "Key2" => "Value"
),

"anotherarray" => array(
    "AnotherKey" => "AnotherValue", 
    "ItsAnArray" => array("key" => "value"),
),

);

It's saying the errors are with every use of $this->config in System.php. What am I doing wrong?

6
  • 1
    Why would you encode/decode an array to JSON in the same line? Commented Feb 10, 2014 at 19:13
  • It was an answer on my previous post: stackoverflow.com/questions/21684375/… Commented Feb 10, 2014 at 19:14
  • That was some go horse programming, huh? Please post the complete error detail with lines. Commented Feb 10, 2014 at 19:19
  • @Will it's really bad. See my comment on that answer in your previous question. Commented Feb 10, 2014 at 19:20
  • As for your 'non-object' issue, do you run constructor for System object when use it? I can see where you're getting new instance of Utils object, but not System. Commented Feb 10, 2014 at 19:24

1 Answer 1

0

You can convert the $config parameter in constructor by using

public function __construct($config) {
    $this->config = (object) $config;
}

But, remember: converting array into a object is not recursively. So, you'll have to access the property using this:

$util = new Util($config);

print_r($util->config->array['key']);

As the question still in the same error, try using this:

require_once("Utils.php");
class System extends Utils {

   public function __construct($config){
      parent::__construct($config);
   }

   // a bunch of functions
   public function bind($port) {
      // stuff
      $this->writeOutput("Host: {$this->config->MySQL->Host}");
   }
}

$v = new System($array);
Sign up to request clarification or add additional context in comments.

1 Comment

It still says "trying to get a property of a non-object".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.