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?

James
  • 261
  • 2
  • 5
  • 16
  • 1
    Why would you encode/decode an array to JSON in the same line? – enapupe Feb 10 '14 at 19:13
  • It was an answer on my previous post: http://stackoverflow.com/questions/21684375/convert-a-multidimensional-array-to-an-xml-object-in-php – James Feb 10 '14 at 19:14
  • That was some go horse programming, huh? Please post the complete error detail with lines. – enapupe Feb 10 '14 at 19:19
  • @Will it's really bad. See my comment on that answer in your previous question. – ozahorulia Feb 10 '14 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. – ozahorulia Feb 10 '14 at 19:24
  • I thought that it would inherit $this->config as it extends Utils. – James Feb 10 '14 at 19:27

1 Answers1

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);
mend3
  • 506
  • 4
  • 15