Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Car
- {
- private $brand;
- private $model;
- private $year;
- public function __construct($brand, $model, $year)
- {
- $this->brand = $brand;
- $this->model = $model;
- $this->year = $year;
- }
- public function toJson()
- {
- $arr = array(
- 'brand' => $this->brand,
- 'model' => $this->model,
- 'year' => $this->year,
- );
- return json_encode($arr);
- }
- public static function fromJson($json)
- {
- $arr = json_decode($json, true);
- return new self(
- $arr['brand'],
- $arr['model'],
- $arr['year']
- );
- }
- }
- // original object
- echo 'car1: ';
- $car1 = new Car('Hyundai', 'Tucson', 2010);
- var_dump($car1);
- // serialize
- echo 'car1class: ';
- $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.
- var_dump($car1class);
- echo 'car1json: ';
- $car1Json = $car1->toJson();
- var_dump($car1Json);
- // static recreation with direct invocation. can only do this if you know the class name in code.
- echo 'car2: ';
- $car2 = Car::fromJson($car1Json);
- var_dump($car2);
- // dynamic recreation with reflection. can do this when you only know the class name at runtime as a string.
- echo 'car3: ';
- $car3 = (new ReflectionMethod($car1class, 'fromJson'))->invoke(null, $car1Json);
- var_dump($car3);
Add Comment
Please, Sign In to add comment