<?php trait PropertyValidator { private function validate(string $prop, mixed $value): mixed { $validator = (new ReflectionObject($this))->getProperty($prop)->getAttributes()[0]?->newInstance(); if (!$validator->validate($value)) { throw new \InvalidArgumentException(); } return $value; } } #[\Attribute] class Str { public function __construct(public readonly int $maxLength) {} public function validate(string $val): bool { return strlen($val) <= $this->maxLength; } } class User { use PropertyValidator; #[Str(5)] public string $name { set => $this->validate(__PROPERTY__, $value); } public function __construct( ) {} } $u = new User(); // This should be fine. $u->name = 'Crell'; // This throws. $u->name = 'Alfredo';
You have javascript disabled. You will not be able to edit any code.
Here you find the average performance (time & memory) of each version. A grayed out version indicates it didn't complete successfully (based on exit-code).