Skip to content

Instantly share code, notes, and snippets.

@zburgermeiszter
Last active September 10, 2020 18:40
Show Gist options
  • Save zburgermeiszter/7dc5e65b06bb34a325a0363726fd8e14 to your computer and use it in GitHub Desktop.
Save zburgermeiszter/7dc5e65b06bb34a325a0363726fd8e14 to your computer and use it in GitHub Desktop.
PHP JsonSerializable with Reflection in Trait
<?php
trait JsonSerialize
{
function jsonSerialize()
{
$reflect = new ReflectionClass($this);
$props = $reflect->getProperties(ReflectionProperty::IS_STATIC | ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE);
$propsIterator = function() use ($props) {
foreach ($props as $prop) {
yield $prop->getName() => $this->{$prop->getName()};
}
};
return iterator_to_array($propsIterator());
}
}
class C implements JsonSerializable
{
use JsonSerialize;
private $x = 0;
protected $y = "z";
}
$c = new C();
echo json_encode($c);
/*
{
"x":0,
"y":"z"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment