Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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?

share|improve this question
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: stackoverflow.com/questions/21684375/… – 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. – Hast 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. – Hast Feb 10 '14 at 19:24
up vote 0 down vote accepted

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);
share|improve this answer
    
It still says "trying to get a property of a non-object". – James Feb 10 '14 at 20:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.