Take the 2-minute tour ×

I'm trying to dynamically create object properties for JSON representation of an object. The class User will feature some default properties (setted in __construct). I'm using custom object instead of arrays because i prefer object oriented style (and i need also custom setter/getters methods).

However the first try gives me:

Strict standards: Creating default object from empty value.

even if the code actually works (and json_encode shows the right output):


class User
    protected $data = array();

    public function __set($property, $value)
        $this->data[$property] = $value;


$u = new User();
$u->name = "James Smith"; // Works
$u->status->active   = false; // Fail
$u->status->modified = time();



I think it's because the call $u->status->active, when property $u->status does not exist yet. Do you know how to fix this?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

OK I sorted that out for you :) It was interesting.

First, you have not initialized the status property. So in theory, this should have been sufficient:

$u->status = new StdClass;

However, it is more complicated than this. Even if you do it, it won't work. That is because you are setting your fields in the data array, but you are never GETTING THEM OUT from there!

So when you access a field ($u->status) you are NOT taking the field you have just set: you are accessing an unset object property. If you try to print $u->name after setting it, you will not get anything, because you have not created a getter function which would read your data array.

You should either create a getter, or delete the setter (it will work anyway, but may not be what you need).

If you comment out the setter, everything works without warnings. See this simplified version:



class User


$u = new User();
$u->name = "James Smith";
$u->status = new StdClass;    // Comment this line and you will get the strict warning
$u->status->active   = false;

share|improve this answer
Thanks for your time. Any chance to get rid (maybe using __set()) of new stdClass() statement? –  gremo Dec 22 '11 at 1:42
Well, you need to initialize the status field, and then you need to create an object there, in order to be able to set the active field on it. So either this, or you create a new function like "$u->newObjectField($fieldName)" which creates a new object at fieldName and initializes it. –  Palantir Dec 23 '11 at 7:26
Hi, did you solve your problem? If you found this useful, please upvote or accept it. –  Palantir Dec 27 '11 at 10:53

Your Answer


