Last active
September 10, 2020 18:40
-
-
Save zburgermeiszter/7dc5e65b06bb34a325a0363726fd8e14 to your computer and use it in GitHub Desktop.
PHP JsonSerializable with Reflection in Trait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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