3v4l.org

run code in 300+ PHP versions simultaneously
<?php function doSerialize($obj) { $data = $obj->__serialize(); // produce a string out of the data array return $data; } function doUnserialize($class, $data) { // $data will contain a string with all information about class, self-references etc $new = (new ReflectionClass($class))->newInstanceWithoutConstructor(); // this happens before calling __unserialize internally for self refferences $data['selfref'] = $new; return $class::__unserialize($new, $data); } class Test { public $prop; public $selfref; function __construct() { $this->prop = 'prop'; $this->selfref = $this; } public function __serialize(): array { return ['prop' => $this->prop]; } public static function __unserialize(self $new, array $data): self { $new->prop = $data['prop']; $new->selfref = $data['selfref']; return $new; } } class Test2 { public $prop; public $selfref; function __construct() { $this->prop = 'prop'; $this->selfref = $this; } public function __serialize(): array { return ['prop' => $this->prop]; } public static function __unserialize(self $new, array $data): self { $new = (new ReflectionClass(self::class))->newInstanceWithoutConstructor(); $new->prop = $data['prop']; $new->selfref = $new; return $new; } } $a1 = new Test; $adata = doSerialize($a1); $a2 = doUnserialize('Test', $adata); var_dump($a2, $a2 === $a2->selfref); $b1 = new Test2; $bdata = doSerialize($b1); $b2 = doUnserialize('Test2', $bdata); var_dump($b2, $b2 === $b2->selfref);
Output for 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
Fatal error: Method Test::__unserialize() must take exactly 1 argument in /in/AbQ2s on line 32
Process exited with code 255.
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Fatal error: Method Test::__unserialize() must take exactly 1 argument in /in/AbQ2s on line 32
Process exited with code 255.
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33
object(Test)#3 (2) { ["prop"]=> string(4) "prop" ["selfref"]=> *RECURSION* } bool(true) object(Test2)#6 (2) { ["prop"]=> string(4) "prop" ["selfref"]=> *RECURSION* } bool(true)

preferences:
147.62 ms | 402 KiB | 212 Q