2

Enhance json functionality

Enhance the current JSON functionality + Add the possibility to also display private properties with json_encode() You could go for something like the JsonSerializable Interface, but every object inside the object has to implement this. + Make decoding a json into a concrete class easier At the moment every json object gets decoded to the stdClass object. So you would need to write a mapper for every class to cast the stdClass object to the actual one With the current state of PHP you can serve jsons with the help of the JsonSerializable Interface, but its not clean. The real challange is to decode a given json string to an actual PHP object. There is no JsonUnserializable interface (I did not find a concrete answer why is that) Lets suggest there would be an JsonUnserializable interface. Still you would need to map your properties to the json elements. Same for the JsonSerializeable interface. This should not be neccessary and work out of the box. Summary: - json_encode() (or a new function) should display all properties not only public ones. So you have a real json with all properties. - json_decode() should decode into a concrete object, or it should be possible to cast a StdClass object into another concrete class object. Overall I would wish that PHP 8 would provide a better way to handle the communication with objects (json, xml, ...). Microservices are popping up everywhere and almost every application needs an API (Rest, jGraph) for communication. It would be amazing if there is a clear way to automatically convert an object into a json and back into an object without the need to manually map everything. ``` php class User { private $id; private $name; protected $protectedProperty; public $publicProperty; public function __construct() { $this -> id = 2; $this -> name = "Please Implement"; $this -> protectedProperty = "protected"; $this -> publicProperty = "public"; } } $user = new User(); $jsonUser = json_encode( $user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ); echo "json_encode(): " . $jsonUser; echo "-----"; print_r( json_decode( $jsonUser ) ); ``` Output: ``` json_encode(): { "publicProperty": "public" } ----- stdClass Object ( [publicProperty] => public ) ```
kylekatarnls · 2 months ago

Exception · 2 months ago