fork(10) download
  1. <?php
  2.  
  3. abstract class JsonDeserializer
  4. {
  5. /**
  6.   * @param string|array $json
  7.   * @return $this
  8.   */
  9. public static function Deserialize($json)
  10. {
  11. $className = get_called_class();
  12. $classInstance = new $className();
  13. if (is_string($json))
  14. $json = json_decode($json);
  15. foreach ($json as $key => $value)
  16. $classInstance->{$key} = $value;
  17. return $classInstance;
  18. }
  19. /**
  20.   * @param string $json
  21.   * @return $this[]
  22.   */
  23. public static function DeserializeArray($json)
  24. {
  25. $json = json_decode($json);
  26. $items = [];
  27. foreach ($json as $item)
  28. $items[] = self::Deserialize($item);
  29. return $items;
  30. }
  31. }
  32.  
  33. class MyObject extends JsonDeserializer
  34. {
  35. /** @var string */
  36. public $property1;
  37.  
  38. /** @var string */
  39. public $property2;
  40.  
  41. /** @var string */
  42. public $property3;
  43.  
  44. /** @var string */
  45. public $array1;
  46. }
  47.  
  48. $objectInstance = new MyObject();
  49. $objectInstance->property1 = 'Value 1';
  50. $objectInstance->property2 = 'Value 2';
  51. $objectInstance->property3 = 'Value 3';
  52. $objectInstance->array1 = ['Key 1' => 'Value 1', 'Key 2' => 'Value 2'];
  53. var_dump($objectInstance);
  54.  
  55. $jsonSerialized = json_encode($objectInstance);
  56. var_dump($jsonSerialized);
  57.  
  58. $deserializedInstance = MyObject::Deserialize($jsonSerialized);
  59. var_dump($deserializedInstance);
Success #stdin #stdout 0.04s 52480KB
stdin
Standard input is empty
stdout
object(MyObject)#1 (4) {
  ["property1"]=>
  string(7) "Value 1"
  ["property2"]=>
  string(7) "Value 2"
  ["property3"]=>
  string(7) "Value 3"
  ["array1"]=>
  array(2) {
    ["Key 1"]=>
    string(7) "Value 1"
    ["Key 2"]=>
    string(7) "Value 2"
  }
}
string(114) "{"property1":"Value 1","property2":"Value 2","property3":"Value 3","array1":{"Key 1":"Value 1","Key 2":"Value 2"}}"
object(MyObject)#2 (4) {
  ["property1"]=>
  string(7) "Value 1"
  ["property2"]=>
  string(7) "Value 2"
  ["property3"]=>
  string(7) "Value 3"
  ["array1"]=>
  object(stdClass)#4 (2) {
    ["Key 1"]=>
    string(7) "Value 1"
    ["Key 2"]=>
    string(7) "Value 2"
  }
}