note 129122 added to language.attributes.syntax

From: Date: Sat, 23 Dec 2023 12:38:00 +0000
Subject: note 129122 added to language.attributes.syntax
Groups: php.notes 
Request: Send a blank email to php-notes+get-221076@lists.php.net to get a copy of this message
It wasn't obvious to me for a while but you can subclass attributes https://3v4l.org/TrMTe <?php #[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); } } class MyClass { #[IntegerPropertyAttributes('prop', 'property: ', 5, 0, 10, 1)] public int $prop; } $refl = new ReflectionProperty('MyClass', 'prop'); $attributes = $refl->getAttributes(); foreach ($attributes as $attribute) { var_dump($attribute->getName()); var_dump($attribute->getArguments()); var_dump($attribute->newInstance()); } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.157.134 (proxied: 101.182.230.195) ---- Manual Page -- https://php.net/manual/en/language.attributes.syntax.php Edit -- https://main.php.net/note/edit/129122 Del: integrated -- https://main.php.net/note/delete/129122/integrated Del: useless -- https://main.php.net/note/delete/129122/useless Del: bad code -- https://main.php.net/note/delete/129122/bad+code Del: spam -- https://main.php.net/note/delete/129122/spam Del: non-english -- https://main.php.net/note/delete/129122/non-english Del: in docs -- https://main.php.net/note/delete/129122/in+docs Del: other reasons-- https://main.php.net/note/delete/129122 Reject -- https://main.php.net/note/reject/129122 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221076) next »