This article describes a workaround for PHP Json_encode that does not support object private properties, Json_encode can convert an object to JSON format and use Json_decode to revert to an object.
However, if the object contains a private property, the private property is lost when the Json_encode is executed.
Example: Json_encode lost Object Private Property
<?php//user Class class user{public $id = 1; Public $name = ' fdipzone '; Public $profession = ' Programmer '; Private $age = 18;} Object $ouser = new user;//Json_encode$json = Json_encode ($oUser); echo $json;//Json_decode$ouser = Json_decode ($json); var _dump ($oUser);? >
Output:
{"id": 1, "name": "Fdipzone", "Profession": "Programmer"}object (StdClass) [2] public ' id ' = = int 1 public ' Name ' = ' + string ' fdipzone ' (length=8) public ' profession ' = ' = String ' Programmer ' (length=10)
After Json_encode is executed, the private attribute age is lost.
Json_encode the object's private property loss resolution
The modified code is as follows:
<?php//user Class class implements jsonserializable{public $id = 1; Public $name = ' fdipzone '; Public $profession = ' Programmer '; Private $age =; Implements an abstract class method that specifies the data that needs to be serialized JSON public function jsonserialize () { $data = []; foreach ($this as $key = + $val) { if ($val!== null) $data [$key] = $val; } return $data; }} Object $ouser = new user;//Json_encode$json = Json_encode ($oUser); echo $json;//Json_decode$ouser = Json_decode ($json); var _dump ($oUser);? >
Output:
{"id": 1, "name": "Fdipzone", "Profession": "Programmer", "Age": 18}object (StdClass) [2] public ' id ' = = int 1 Public ' name ' = = String ' Fdipzone ' (length=8) public ' profession ' = ' = String ' Programmer ' (length=10) C16/>public ' age ' = int 18
After specifying the data that needs to be serialized into JSON, Json_encode can read to the private attribute age.
This article explains the PHP Json_encode does not support the object of the private property of the relevant knowledge, more relevant content please focus on the PHP Chinese web.