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):
<?php
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();
var_dump(json_encode($u));
?>
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?
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:
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: