This article describes that the PHP Json_encode does not support the solution of object private properties, Json_encode can convert objects to JSON format and use Json_decode to revert to objects.
However, if the object contains private properties, the private property is lost when the Json_encode is executed.
Example: Json_encode lost object Private Property
<?php
//user class
user{public
$id = 1;
Public $name = ' fdipzone ';
Public $profession = ' Programmer ';
Private $age =;
}
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)
The private property age was lost after the Json_encode was executed.
Json_encode object's private property loss resolution
We can modify the class so that it implements the interface method Jsonserialize of the Jsonserializable abstract class, specifying the data that needs to be serialized into JSON.
About Jsonserializable::jsonserialize Method can refer to official website: http://php.net/manual/zh/jsonserializable.jsonserialize.php
The modified code is as follows:
<?php
//User classes Class
user implements jsonserializable{public
$id = 1;
Public $name = ' fdipzone ';
Public $profession = ' Programmer ';
Private $age =;
Implements an abstract class method that specifies the data public
function jsonserialize () {
$data = [] that needs to be serialized JSON;
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":
Object (StdClass) [2] public
' ID ' => int 1 public
' name ' => string ' Fdipzone ' (length=8) public
' Profession ' => string ' Programmer ' (length=10) public
' age ' => int 18
After specifying the data that needs to be serialized into JSON, Json_encode can read to the private attribute age.