Skip to content

Instantly share code, notes, and snippets.

@rwsite
Last active January 23, 2024 20:38
Show Gist options
  • Save rwsite/845cc63debaa7a3e33d9bd87d673241d to your computer and use it in GitHub Desktop.
Save rwsite/845cc63debaa7a3e33d9bd87d673241d to your computer and use it in GitHub Desktop.
Пример создания и использования атрибутов PHЗ 8
<?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