3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php class Validator { const GREATER = [self::class, 'greater']; const IS_TYPE = [self::class, 'isType']; public static function all(...$rules) { foreach ($rules as $def) { $rule = array_shift($def); if ($rule(...$def)) { continue; } return false; } return true; } public static function greater($value, $compare) : bool { return $value > $compare; } public static function isType($value, $type) : bool { return gettype($value) === $type; } } class Model { const RULES = [ 'foo' => [ 'integer', // shorthand for [Validator::IS_TYPE, 'integer'] [Validator::GREATER, 10] ] ]; protected $foo; public function set($name, $value) { if ($this->isValid($name, $value)) { $this->$name = $value; return; } throw new Exception("{$name} cannot be {$value}"); } function isValid($name, $value) : bool { $rules = []; foreach (self::RULES[$name] as $rule) { // convenience: turn strings into typehints if (is_string($rule)) { $rules[] = [Validator::IS_TYPE, $value]; continue; } // ... other convenience parsing ... // for fully defined rules, just add value arg at proper spot array_splice($rule, 1, 0, $value); $rules[] = $rule; } return Validator::ALL($rules); } } $m = new Model; $m->set('foo', 15); var_dump($m); $m->set('foo', 7);
based on OXc1r
Output for 7.0.0 - 7.3.0alpha1
Fatal error: Uncaught Error: First array member is not a valid class name or object in /in/iRMov:11 Stack trace: #0 /in/iRMov(62): Validator::all(Array) #1 /in/iRMov(38): Model->isValid('foo', 15) #2 /in/iRMov(68): Model->set('foo', 15) #3 {main} thrown in /in/iRMov on line 11
Process exited with code 255.
Output for hhvm-3.15.4
Fatal error: Uncaught Error: Arrays are not allowed in class constants in /in/iRMov:5 Stack trace: #0 {main}
Process exited with code 255.
Output for 5.6.0 - 5.6.30
Parse error: syntax error, unexpected ':', expecting ';' or '{' in /in/iRMov on line 17
Process exited with code 255.