Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lessmore92/4499d33e269ba3cc19f5b0391fac7a11 to your computer and use it in GitHub Desktop.
Save lessmore92/4499d33e269ba3cc19f5b0391fac7a11 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