Attribute 구문

Attributes 구문에는 여러 부분이 있습니다. 첫째, attribute 선언은 항상 시작 #[ 및 해당 종료 ]로 묶입니다. 내부에는 하나 이상의 attribute이 쉼표로 구분되어 나열됩니다. attribute 이름은 네임스페이스 기본 사용에 설명된 대로 규정되지 않은, 규정된 또는 완전한 이름입니다. attribute에 대한 인수는 선택 사항이지만 일반적인 괄호()로 묶입니다. attributes에 대한 인수는 리터럴 값 또는 상수 표현식일 수 있습니다. 위치 및 명명된 인수 구문을 모두 사용할 수 있습니다.

Attribute 이름과 해당 인수는 리플렉션 API를 통해 Attribute 인스턴스가 요청될 때 클래스로 확인되고 인수가 해당 생성자로 전달됩니다. 따라서 각 Attribute에 대해 클래스를 도입해야 합니다.

예제 #1 Attribute 구문

                  
<?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
{
}