You should implement the JsonSerializable interface (secure.php.net/manual/en/jsonseria...), then you can just pass your object to json_encode() and it'll do the right thing. That'll also handle JSON serializing an array of them, without having to serialize each one manually (just serialize the array and it'll call the jsonSerialize method on each one).
Yah sure, but the downside of implementing JsonSerializable is that i will need a different return value to jsonSerialize in all of my models because i have to construct an array representation of the class every time.
Good point. I forgot that traits can't implement interfaces in PHP. I use Hack at work, which is based on PHP but traits are able to implement interfaces when using Hack.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
You should implement the
JsonSerializable
interface (secure.php.net/manual/en/jsonseria...), then you can just pass your object tojson_encode()
and it'll do the right thing. That'll also handle JSON serializing an array of them, without having to serialize each one manually (just serialize the array and it'll call thejsonSerialize
method on each one).Yah sure, but the downside of implementing
JsonSerializable
is that i will need a different return value tojsonSerialize
in all of my models because i have to construct an array representation of the class every time.Good point. I forgot that traits can't implement interfaces in PHP. I use Hack at work, which is based on PHP but traits are able to implement interfaces when using Hack.