json_encode PHP 个具有受保护属性的对象

json_encode PHP objects with their protected properties

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

我读过其他答案,建议我向对象添加一个 toJson() 函数,但这可能对我帮助不大。在大多数情况下,我有一个对象数组,我对数组本身执行编码。

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

return json_encode($array);

是的,我可以遍历这个数组并在每个具有这种方法的元素上调用 toJson(),但这似乎不对。有什么方法可以使用魔术方法来实现吗?

您可以实现 JsonSerializable interface in your classes so you have full control over how it is going to be serialized. You could also create a Trait 以防止复制粘贴序列化方法:

<?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 来做你想做的事:

<?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]));