json_encode PHP对象及其受保护的属性 [英] json_encode PHP objects with their protected properties

查看:138
本文介绍了json_encode PHP对象及其受保护的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以设置PHP对象,以便当我尝试将其转换为JSON时,将显示其所有受保护的属性?

Is there any way I can set up PHP objects so that when I try to convert them to JSON, all of their protected properties will be shown?

我阅读了其他答案,暗示我向对象添加了toJson()函数,但这可能对我没有很大帮助.在大多数情况下,我有一个对象数组,并对数组本身执行编码.

I have read other answers suggesting I add a toJson() function to the object, but that may not really help me a great lot. In most cases, I have an array of objects and I perform the encode on the array itself.

$array = [
    $object1, $object2, $object3, 5, 'string', $object4
];

return json_encode($array);

是的,我可以遍历此数组并在具有此方法的每个元素上调用toJson(),但这似乎并不正确.有没有办法我可以使用魔术方法来实现这一目标?

Yes, I can loop through this array and call toJson() on every element that has such method, but that just doesn't seem right. Is there a way I can use magic methods to achieve this?

推荐答案

您可以实现类中的JsonSerializable 接口,因此您可以完全控制它的序列化方式.您还可以创建 Trait ,以防止复制粘贴序列化方法:

You can implement the JsonSerializable interface in your classes so you have full control over how it is going to be serialized. You could also create a Trait to prevent copy pasting the serializing method:

<?php

trait JsonSerializer {
    public function jsonSerialize()
    {
        return get_object_vars($this);
    }
}

class Foo implements \JsonSerializable 
{
    protected $foo = 'bar';

    use JsonSerializer;
}

class Bar implements \JsonSerializable 
{
    protected $bar = 'baz';

    use JsonSerializer;   
}

$foo = new Foo;
$bar = new Bar;

var_dump(json_encode([$foo, $bar]));

或者,您可以使用 reflection 来完成您想要的事情:

Alternatively you could use reflection to do what you want:

<?php

class Foo
{
    protected $foo = 'bar';
}

class Bar
{
    protected $bar = 'baz';
}

$foo = new Foo;
$bar = new Bar;

class Seriailzer
{
    public function serialize($toJson)
    {
        $data = [];

        foreach ($toJson as $item) {
            $data[] = $this->serializeItem($item);
        }

        return json_encode($data);
    }

    private function serializeItem($item)
    {
        if (!is_object($item)) {
            return $item;
        }

        return $this->getProperties($item);
    }

    private function getProperties($obj)
    {
        $rc = new ReflectionClass($obj);

        return $rc->getProperties();
    }
}

$serializer = new Seriailzer();

var_dump($serializer->serialize([$foo, $bar]));

这篇关于json_encode PHP对象及其受保护的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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