If you're using PHP 5.3 (or earlier), you can't really do what you're asking for easily. You won't get the methods encoded in JSON because JSON is a data format and doesn't include functions, and you won't get the property because it's a private property. You know this much already, but it's worth re-iterating to point out that you're right, it's not easy. Even writing the getter as a magic __get()
method to turn it into a read-only public property won't work in this case.
In PHP 5.3, there are a couple of work arounds you could use.
Reflection
. PHP includes a Reflection API, which allows you to access details about objects and classes, including reading values from private members. Obviously, however, this would mean writing a fair bit of code to get at the value, and it won't be fast either.
Write the json_encode
call inside the class. That way you can include private properties. I would suggest using get_object_vars($this)
inside the object to get at the private properties in a JSON friendly way.
If you're using PHP 5.4, you have an additional option:
- PHP 5.4 introduces a
JsonSerializable
interface. Add implements JsonSerializable
to your class, and write a method called jsonSerialize()
. This method should return the data that you want to be in the JSON string. You can include or exclude whichever public or private properties you want.
PHP 5.5 hasn't been released yet, but it will add another option for you:
PHP 5.5 will introduce a more complex syntax for defining properties, which will allow you to define properties as public but read-only, or to include more complex logic for them in the getter and setter, but still have them as properties. It will work much like the __get()
and __set()
methods do now, but with the variables explicitly defined as properties, which will mean that they should be accessible to the JSON serialiser, whereas currently with __get()
they're not.
[EDIT] - note, the above paragraph is incorrect; the feature described did not make it into the PHP 5.5 release. Too early yet to say yet whether it'll get into 5.6 or not.
Hope that helps.