3v4l.org

run code in 300+ PHP versions simultaneously
<?php class ValidationError { private array $errors = []; public function addError(string $fieldName, string $error) { $this->errors[$fieldName][] = $error; } public function haveErrors() : bool { return 0 !== count($this->errors); } public function printErrors() : void { print_r($this->errors); } } class UserForm { public string $name; public int $age; public function __construct(string $name, int $age) { $this->name = $name; $this->age = $age; } } class User { private string $name; private int $age; private function __construct(string $name, int $age) { $this->name = $name; $this->age = $age; } public static function createFromForm(UserForm $form) : User|ValidationError { $result = static::validate([ 'name' => $form->name, 'age' => $form->age, ]); if ($result) { return $result; } return new User($form->name, $form->age); } private static function validate(array $data) : ?ValidationError { $validationError = new ValidationError; if (20 < mb_strlen($data['name'])) { $validationError->addError('name', 'Too long. 20 chars only.'); } if (false !== mb_strpos($data['name'], 'хуй')) { $validationError->addError('name', 'Sam ti hui.'); } if (0 === $data['age']) { $validationError->addError('age', 'Too young.'); } if ($validationError->haveErrors()) { return $validationError; } return null; } } $correctForm = new UserForm('Test', 11); $result = User::createFromForm($correctForm); if ($result instanceof ValidationError) { $result->printErrors(); } $incorrectForm = new UserForm('Ты хуй', 0); $result = User::createFromForm($incorrectForm); if ($result instanceof ValidationError) { $result->printErrors(); }
Output for 8.1.23 - 8.1.28, 8.2.10 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
Array ( [name] => Array ( [0] => Sam ti hui. ) [age] => Array ( [0] => Too young. ) )
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 Array ( [name] => Array ( [0] => Sam ti hui. ) [age] => Array ( [0] => Too young. ) )
Output for 7.4.0 - 7.4.10
Parse error: syntax error, unexpected '|', expecting ';' or '{' in /in/s9Eb9 on line 46
Process exited with code 255.
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.22
Parse error: syntax error, unexpected 'array' (T_ARRAY), expecting function (T_FUNCTION) or const (T_CONST) in /in/s9Eb9 on line 5
Process exited with code 255.

preferences:
103 ms | 402 KiB | 95 Q