将json_encode应用到类时如何忽略特定值 [英] How to ignore specific values when applying json_encode to class

查看:127
本文介绍了将json_encode应用到类时如何忽略特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编码为json时,是否可以忽略php中某个类的特定类属性.

Is there a way to ignore specific class attributes of a class in php when encoding to json.

例如,在具有杰克逊库的Java中,我可以使用@JsonIgnore注释全局变量以实现此目的. php中有什么可比的(最好是本地的)吗?

For example in java with the jackson library I can annotate globals with @JsonIgnore to achieve this. Is there anything comparable (preferably native) in php??

推荐答案

一种方法是利用 JsonSerializable接口.这样,您可以创建在类上调用json_encode()时调用的函数.

One method is to utilize the JsonSerializable interface. This lets you create a function that's called when json_encode() is called on your class.

例如:

class MyClass implements JsonSerializable{
    public $var1, $var2;

    function __construct($a1, $a2){
        $this->var1 = $a1;
        $this->var2 = $a2;
    }

    // From JsonSerializable
    public function jsonSerialize(){
        return ['var1' => $this->var1];
    }
}

因此,当调用json_encode()时,将仅对var1进行编码.

So, when json_encode() is called, only var1 will be encoded.

$myObj = new MyClass(10, 20);
echo json_encode($myObj); // {"var1":10}

演示: https://eval.in/103959

注意:这仅适用于PHP 5.4 +

Note: This only works on PHP 5.4+

这篇关于将json_encode应用到类时如何忽略特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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