PHP json_encode 类私有成员 [英] PHP json_encode class private members

查看:33
本文介绍了PHP json_encode 类私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 PHP 中的一些对象进行 JSON 编码,但我面临一个问题:我想对由类私有成员保存的数据进行编码.我发现这段代码通过调用一个编码函数来编码这个对象:

I'm trying to JSON encode some objects in PHP, but I'm facing a problem: I want to encode data which is kept by a class private members. I found this piece of code to encode this object by calling an encode function like:

public function encodeJSON() 
{ 
    foreach ($this as $key => $value) 
    { 
        $json->$key = $value; 
    } 
    return json_encode($json); 
}

但是,这仅在我要编码的对象内部不包含其他对象时才有效,就是这种情况.我怎样才能不仅对外部"对象进行编码,还要对作为对象的任何成员进行编码?

However, this only works if the object I want to encode does not contain other objects inside, which is the case. How can I do to encode not only the "outer" object, but encode as well any members that are objects too?

推荐答案

序列化具有私有属性的对象的最佳方法是实现 JsonSerializable 接口,然后实现自己的 JsonSerialize 方法来返回需要序列化的数据.

The best method to serialize an object with private properties is to implement the JsonSerializable interface and then implement your own JsonSerialize method to return the data you require to be serialized.

<?php

class Item implements JsonSerializable
{
    private $var;
    private $var1;
    private $var2;

    public function __construct()
    {
        // ...
    }

    public function jsonSerialize()
    {
        $vars = get_object_vars($this);

        return $vars;
    }
}

json_encode 现在将正确序列化您的对象.

json_encode will now serialize your object correctly.

这篇关于PHP json_encode 类私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆