Home > Article > Backend Development > Explanation on php json_encode not supporting object private attributes
This article introduces the solution for php json_encode that does not support the private properties of objects. json_encode can convert the object into json format, and use json_decode to restore it to the object.
But if the object contains private attributes, the private attributes will be lost after json_encode is executed.
<?php// 用户类class user{ public $id = 1; public $name = 'fdipzone'; public $profession = 'programmer'; private $age = 18; }// 对象$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 executing json_encode, the private attribute age is lost.
The modified code is as follows:
<?php// 用户类class user implements JsonSerializable{ public $id = 1; public $name = 'fdipzone'; public $profession = 'programmer'; private $age = 18; // 实现的抽象类方法,指定需要被序列化JSON的数据 public function jsonSerialize() { $data = []; foreach ($this as $key=>$val){ if ($val !== null) $data[$key] = $val; } return $data; } }// 对象$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) public 'age' => int 18
After specifying the data that needs to be serialized into JSON, json_encode can read the private attribute age.
This article explains the relevant knowledge that php json_encode does not support object private attributes. For more related content, please pay attention to the php Chinese website.
Related recommendations:
Explanation on PHP generating unique RequestID class related content
MySQL View database table capacity size
Detailed explanation of a singleton mode Mysql operation class encapsulated by PHP
The above is the detailed content of Explanation on php json_encode not supporting object private attributes. For more information, please follow other related articles on the PHP Chinese website!