3v4l.org

run code in 300+ PHP versions simultaneously
<?php class DataObjectSecurityException extends Exception {}; abstract class DataObject { private $key; public function __construct(array $fields, string $key) { foreach($fields as $field => $value) { $this->$field = $value; } $this->key = $key; } public function export(string $key) { if ($key !== $this->key) { throw new DataObjectSecurityException("you are not authorized"); } return get_object_vars($this); } } class User extends DataObject { protected $id; protected $name; protected $hairColor; public function hi() { echo "Hi {$this->name}. You have nice {$this->hairColor} hair." . PHP_EOL; } public function dyeHair(string $color) { $this->hairColor = $color; } } // sample data as would be extracted from DB: $userData = ['id' => 11, 'name' => 'Jane Doe', 'hairColor' => 'brown']; $key = uniqid(); $user = new User($userData, $key); $user->hi(); echo "changing hair color" . PHP_EOL; $user->dyeHair('blue'); $user->hi(); // now retrieve the data if we want to update the DB $newUserData = $user->export($key); echo "new user data:" . PHP_EOL; var_dump($newUserData);

preferences:
27.87 ms | 402 KiB | 5 Q