您可以在类中实现
JsonSerializable接口,这样您就可以完全控制它的序列化方式.您还可以创建一个
Trait以防止复制粘贴序列化方法:
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来做你想做的事:
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]));