json_encode类时丢失私有属性和受保护属性处理方法

<?php
header("Content-Type: text/html;charset=utf-8");

class a implements JsonSerializable{

    public $b1 = 1;
    private $b2 = 2;
    protected $b3 = 3;

    // 实现的抽象类方法,指定需要被序列化JSON的数据
    public function jsonSerialize() {
        $data = [];
        foreach ($this as $key=>$val){
           $data[$key] = $val;
        }
        return $data;
    }
}

$json = json_encode(new a);
echo $json;

 

官网文档地址: https://php.net/manual/en/class.jsonserializable.php

posted @ 2019-12-06 11:45  钧一  阅读(462)  评论(0)    收藏  举报