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 git.master, git.master_jit, rfc.property-hooks
Array ( [name] => Array ( [0] => Sam ti hui. ) [age] => Array ( [0] => Too young. ) )

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
33.29 ms | 401 KiB | 8 Q