3v4l.org

run code in 300+ PHP versions simultaneously
<?php readonly class Address { public function __construct( public string $street, public string $city, public string $state, public string $country, public string $postalCode, ){ } } readonly class Person { public function __construct( public string $name, public int $age, public Address $address, ){ } } $bob = new Person('Bob', 32, new Address('123 Main St', 'Testington', 'Test', 'Test', '12345')); $bobJson = json_encode($bob); $decodedBob = json_decode_class($bobJson, Person::class); if ($bob == $decodedBob){ echo 'These are the same person!', PHP_EOL; } else { echo 'We have different people here!', PHP_EOL; } function json_decode_class(string $json, string $class){ return construct_object(json_decode($json), $class); } function construct_object(stdClass $data, string $class){ $rc = new ReflectionClass($class); $properties = $rc->getConstructor()->getParameters(); $constructorArgs = []; foreach ($properties as $prop){ $type = $prop->getType(); if (property_exists($data, $prop->getName())){ $value = $data->{$prop->getName()}; if (!$type->isBuiltin()){ $value = construct_object($value, $type->getName()); } $constructorArgs[$prop->getName()] = $value; } } return $rc->newInstanceArgs($constructorArgs); }
Output for 8.2.10
These are the same person!

preferences:
173.83 ms | 1434 KiB | 20 Q