I\'ve run into an odd problem and I\'m not sure how to fix it. I have several classes that are all PHP implementations of JSON objects. Here\' an illustration of the issue
A late answers but might be useful for others with the same problem.
In PHP < 5.4.0 json_encode
doesn't call any method from the object. That is valid for getIterator, __serialize, etc...
In PHP > v5.4.0, however, a new interface was introduced, called JsonSerializable.
It basically controls the behaviour of the object when json_encode
is called on that object.
Example:
class A implements JsonSerializable
{
protected $a = array();
public function __construct()
{
$this->a = array( new B, new B );
}
public function jsonSerialize()
{
return $this->a;
}
}
class B implements JsonSerializable
{
protected $b = array( 'foo' => 'bar' );
public function jsonSerialize()
{
return $this->b;
}
}
$foo = new A();
$json = json_encode($foo);
var_dump($json);
Outputs:
string(29) "[{"foo":"bar"},{"foo":"bar"}]"