Guest User

Untitled

a guest
Nov 15th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. <?php
  2.  
  3. class Car
  4. {
  5. private $brand;
  6. private $model;
  7. private $year;
  8.  
  9. public function __construct($brand, $model, $year)
  10. {
  11. $this->brand = $brand;
  12. $this->model = $model;
  13. $this->year = $year;
  14. }
  15.  
  16. public function toJson()
  17. {
  18. $arr = array(
  19. 'brand' => $this->brand,
  20. 'model' => $this->model,
  21. 'year' => $this->year,
  22. );
  23.  
  24. return json_encode($arr);
  25. }
  26.  
  27. public static function fromJson($json)
  28. {
  29. $arr = json_decode($json, true);
  30.  
  31. return new self(
  32. $arr['brand'],
  33. $arr['model'],
  34. $arr['year']
  35. );
  36. }
  37. }
  38.  
  39. // original object
  40. echo 'car1: ';
  41. $car1 = new Car('Hyundai', 'Tucson', 2010);
  42. var_dump($car1);
  43.  
  44. // serialize
  45. echo 'car1class: ';
  46. $car1class = get_class($car1); // need the class name for the dynamic case below. this would need to be bundled with the JSON to know what kind of class to recreate.
  47. var_dump($car1class);
  48.  
  49. echo 'car1json: ';
  50. $car1Json = $car1->toJson();
  51. var_dump($car1Json);
  52.  
  53. // static recreation with direct invocation. can only do this if you know the class name in code.
  54. echo 'car2: ';
  55. $car2 = Car::fromJson($car1Json);
  56. var_dump($car2);
  57.  
  58. // dynamic recreation with reflection. can do this when you only know the class name at runtime as a string.
  59. echo 'car3: ';
  60. $car3 = (new ReflectionMethod($car1class, 'fromJson'))->invoke(null, $car1Json);
  61. var_dump($car3);
Add Comment
Please, Sign In to add comment