Attribute 문법

Attribute 문법

Attribute 문법은 몇 가지 핵심 요소로 이루어져 있어요. attribute 선언은 #[로 시작해서 ]로 끝나요. 그 안에는 attribute를 하나 이상 나열할 수 있고, 쉼표로 구분해요. attribute 이름은 네임스페이스 기초에서 설명한 것처럼 unqualified(비한정), qualified(한정), fully-qualified(완전한정) 세 가지 형태 모두를 쓸 수 있어요. attribute에 전달하는 인자는 선택 사항이고 괄호 () 안에 넣어요. 인자에는 리터럴 값이나 상수 표현식만 쓸 수 있고, 위치 인자와 이름 인자 문법이 모두 지원돼요.

attribute 이름과 인자는 하나의 클래스로 해석돼요. 그리고 Reflection 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
{
}