Sintaxe de Atributo

Existem várias partes para a sintaxe de atributos. Primeiro, uma declaração de atributo é sempre incluída com um #[ inicial e um ] final correspondente. Dentro, um ou vários atributos são listados, separados por vírgula. O nome do atributo é um nome não qualificado, qualificado ou totalmente qualificado, conforme descrito em Noções Básicas do Uso de Namespaces. Os argumentos para o atributo são opcionais, mas são colocados entre parênteses (). Os argumentos para atributos só podem ser valores literais ou expressões constantes. Tanto a sintaxe de argumentos posicionais quanto a dos argumentos nomeados podem ser usadas.

Os nomes dos atributos e seus argumentos são resolvidos para uma classe e os argumentos são passados para seu construtor, quando uma instância do atributo é solicitada por meio da API Reflection. Como tal, uma classe deve ser introduzida para cada atributo.

Exemplo #1 Sintaxe de Atributo

<?php
// a.php
namespace MyExample;

use
Attribute;

#[
Attribute]
class
MyAttribute
{
const
VALUE = 'value';

private
$value;

public function
__construct($value = null)
{
$this->value = $value;
}
}

// b.php

namespace Another;

use
MyExample\MyAttribute;

#[
MyAttribute]
#[
\MyExample\MyAttribute]
#[
MyAttribute(1234)]
#[
MyAttribute(value: 1234)]
#[
MyAttribute(MyAttribute::VALUE)]
#[
MyAttribute(array("key" => "value"))]
#[
MyAttribute(100 + 200)]
class
Thing
{
}

#[
MyAttribute(1234), MyAttribute(5678)]
class
AnotherThing
{
}
adicione uma nota

Notas Enviadas por Usuários (em inglês) 1 note

up
3
yarns dot purport0n at icloud dot com
1 year ago
It wasn't obvious to me for a while but you can subclass attributeshttps://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());    }?>
To Top