Forked from zburgermeiszter/JsonSerializableWithReflection.php
Created
November 21, 2018 20:36
-
-
Save lessmore92/4499d33e269ba3cc19f5b0391fac7a11 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