3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * @author ciid */ #[Attribute(Attribute::TARGET_PROPERTY)] class PropertyAttributes { public function __construct( public readonly ?string $name = null, public readonly ?string $label = null, ) {} } #[Attribute(Attribute::TARGET_PROPERTY)] class IntegerPropertyAttributes extends PropertyAttributes { public function __construct( ?string $name = null, ?string $label = null, public readonly ?int $default = null, public readonly ?int $min = null, public readonly ?int $max = null, public readonly ?int $step = null, ) { parent::__construct($name, $label); } } #[Attribute(Attribute::TARGET_PROPERTY)] class FloatPropertyAttributes extends PropertyAttributes { public function __construct( ?string $name = null, ?string $label = null, public readonly ?float $default = null, public readonly ?float $min = null, public readonly ?float $max = null, ) { parent::__construct($name, $label); } } function buildHtmlFormControl(PropertyAttributes $args): string { $html = []; $html[] = "<label>{$args->label} "; $html[] = "<input"; $html[] = " name=\"{$args->name}\""; $html[] = " value=\"{$args->default}\""; switch ($args::class) { case 'IntegerPropertyAttributes': $html[] = " type=\"number\""; $html[] = " min=\"{$args->min}\""; $html[] = " max=\"{$args->max}\""; $html[] = " step=\"{$args->step}\""; break; case 'FloatPropertyAttributes': $html[] = " type=\"number\""; $html[] = " min=\"{$args->min}\""; $html[] = " max=\"{$args->max}\""; break; } $html[] = "></label>\n"; return implode('', $html); } // model class with properties to edit in UI class MyClass { #[IntegerPropertyAttributes('prop','property: ',5,0,10,1)] public int $prop; #[FloatPropertyAttributes('float','double: ',5.5,0.0,9.9)] public float $double; } // index.php implementation $props = [['MyClass', 'prop'], ['MyClass', 'double']]; foreach ($props as $prop) { $refl = new ReflectionProperty($prop[0], $prop[1]); $reflAttrs = $refl->getAttributes(); foreach ($reflAttrs as $attr) { echo buildHtmlFormControl($attr->newInstance()); } }
Output for 8.2.0 - 8.2.29, 8.3.0 - 8.3.28, 8.4.1 - 8.4.15, 8.5.0
<label>property: <input name="prop" value="5" type="number" min="0" max="10" step="1"></label> <label>double: <input name="float" value="5.5" type="number" min="0" max="9.9"></label>

preferences:
52.45 ms | 406 KiB | 5 Q