Problem: I don’t want to expose $myProperty, that is it shouldn’t be public, but I need it to be public just for __toString():
class A
{
protected $myProperty;
public function __toString()
{
return json_encode($this);
}
}
I know that ReflectionProperty class has a method named setAccessible(), but how I’m supposed to use it before returning the string?
EDIT: as per comments, I need compatibility with PHP 5.3.x, that is no JSonSerializable class.
As per PHP 5.3 use
get_object_varsinside the__toString()method:Usage Demo:
Output:
Tip: Create the
JsonSerializableinterface your own and implement thejsonSerialize()method your own to be upwards compatible. Call the function when you need it and/or call it inside__toString():