3v4l.org

run code in 300+ PHP versions simultaneously
<?php abstract class Constraint { public function __construct(array $options = null) { $defaultOptions = $this->getDefaultOptions(); foreach ($this as $option => $value) { if (isset($defaultOptions[$option])) { $this->{$option} = $defaultOptions[$option]; } else { throw new Exception('Ошибочка'); } } if (null !== $options) { $vars = get_object_vars($this); foreach ($options as $option => $value) { if (isset($vars[$option])) { $this->{$option} = $value; } else { throw new Exception('Ошибочка 2'); } } } } abstract protected function getDefaultOptions(): array; } class Length extends Constraint { public $min = 1; public $max; public $minMessage; public $maxMessage; public function __construct(array $options = null) { parent::__construct($options); } protected function getDefaultOptions(): array { return [ 'min' => 2, 'max' => 50, 'minMessage' => 'Значение меньше 2 символов', 'maxMessage' => 'Значение больше 50 символов' ]; } } interface ValidatorInterface { public function validate($value, Constraint $constraint): ?string; } class LengthValidator implements ValidatorInterface { public function validate($value, Constraint $constraint): ?string { if (!$constraint instanceof Length) { throw new Exception(); } $length = mb_strlen(trim($value)); if ($length < $constraint->min) { return $constraint->minMessage; } elseif ($length > $constraint->max) { return $constraint->maxMessage; } return null; } } $length = new Length([ 'min' => 3, 'max' => 50 ]); $lengthValidator = new LengthValidator(); $result = $lengthValidator->validate('Ян', $length); var_dump($result);
Output for 7.1.25 - 7.1.27, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 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
string(48) "Значение меньше 2 символов"
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 string(48) "Значение меньше 2 символов"

preferences:
143.95 ms | 402 KiB | 160 Q