Last active
January 23, 2024 20:38
-
-
Save rwsite/845cc63debaa7a3e33d9bd87d673241d to your computer and use it in GitHub Desktop.
Пример создания и использования атрибутов PHЗ 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Пример создания и использования атрибутов PHP 8 | |
*/ | |
// Объявление атрибута | |
#[Attribute] | |
final class MyAttribute | |
{ | |
public $value; | |
public function __construct(?string $value = null) { | |
$this->value = $value; | |
} | |
} | |
// применение к классу | |
#[ MyAttribute ('hello')] | |
class Thing{} | |
// использование рефлексии для обработки | |
$reflection = new ReflectionClass(Thing::class); | |
$attributes = $reflection->getAttributes(); | |
foreach ($attributes as $attribute) { | |
$attribute->getName(); // full attribute name, e.g. string(11) "MyAttribute" | |
$attribute->getArguments(); // [string(5) "hello"] | |
$attribute->newInstance(); // returns an instance object: object(MyAttribute)#3 (1) { ["value"]=> string(5) "hello" } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment