<?php const KEY_CLASS_NAME = "JSON\\NameSpaceThatAvoidsCollisionsWithFields\\className"; function arrayze($item){ if($item === NULL || is_scalar($item)){ return $item; }elseif(is_object($item)){ $className = get_class($item); $item = (Array)$item; $item[KEY_CLASS_NAME] = $className; } $array = []; foreach($item as $key => $content){ $array[base64_encode($key)] = arrayze($content); } return $array; } function dearrayze($item){ assert(is_object($item) === FALSE); if($item === NULL || is_scalar($item)){ return $item; } $itemClean = []; foreach($item as $key => $content){ $itemClean[base64_decode($key)] = dearrayze($content); } $item = $itemClean; $className = $item[KEY_CLASS_NAME] ?? NULL; if($className !== NULL){ $RC = new ReflectionClass($className); $object = $RC->newInstanceWithoutConstructor(); foreach($item as $property => $content){ if($property === KEY_CLASS_NAME) continue; // 0 ClassName 0 privateProperty // 0 * 0 protectedProperty // publicProperty if(count($p = explode("\0", $property)) === 3){ [$void, $scope, $actualPropertyName] = $p; $scope = $scope === "*" ? $className : $scope; (function() use($actualPropertyName, $content){ $this->{$actualPropertyName} = $content; })->bindTo($object, $scope)(); }else{ $object->{$property} = $content; } } $item = $object; } return $item; } function json_encode_object($object){ $arrayzed = arrayze($object); return json_encode($arrayzed, JSON_PRETTY_PRINT); } function json_decode_object(String $object){ $arrayzed = json_decode($object, TRUE); return dearrayze($arrayzed); } class Father{ public $fpublic = 1; protected $fprotected = 2; private $fprivate = 3; } class Child extends Father{ public $cpublic = 1; protected $cprotected = 2; private $cprivate = 3; public $whoops = "\xc2"; } $child = new Child(); var_dump($child); echo "encoded:\n"; $encoded = json_encode_object($child); var_dump($encoded); echo "decoded:\n"; $decoded = json_decode_object($encoded); var_dump($decoded);
You have javascript disabled. You will not be able to edit any code.
Value for `_results` contains invalid data `array`