라이브러리

[PHP] Attribute::__construct - 새 Attribute 인스턴스를 구성합니다.




PHP 8.0 버전부터 Attribute는 PHP에서 사용할 수 있는 새로운 기능입니다. Attribute는 클래스, 메소드, 프로퍼티에 대해 추가적인 정보를 제공할 수 있습니다. Attribute는 PHP의 Reflection API를 통해 접근할 수 있습니다.

Attribute::__construct

Attribute는 클래스를 정의할 때 `__construct` 메소드를 사용하여 초기화할 수 있습니다. `__construct` 메소드는 Attribute를 생성할 때 호출됩니다.

#hostingforum.kr
php

use Attribute;



class MyAttribute extends Attribute

{

    public function __construct(

        public string $name,

        public int $age,

    ) {}

}



위의 예제에서 `MyAttribute` 클래스는 `Attribute` 클래스를 상속받고 `__construct` 메소드를 정의했습니다. `__construct` 메소드는 `name`과 `age` 프로퍼티를 초기화합니다.

Attribute 사용

Attribute를 사용하려면 클래스, 메소드, 프로퍼티에 `MyAttribute`를 적용해야 합니다.

#hostingforum.kr
php

class User

{

    #[MyAttribute(name: 'John', age: 30)]

    public string $name;



    #[MyAttribute(name: 'Jane', age: 25)]

    public string $email;

}



위의 예제에서 `User` 클래스의 `$name` 프로퍼티와 `$email` 프로퍼티에 `MyAttribute`를 적용했습니다. `MyAttribute`의 `name`과 `age` 프로퍼티는 각각 프로퍼티의 이름과 이메일을 나타냅니다.

Reflection API

Attribute를 사용하여 클래스, 메소드, 프로퍼티에 대한 정보를 얻을 수 있습니다. Reflection API를 사용하여 Attribute를 접근할 수 있습니다.

#hostingforum.kr
php

class User

{

    #[MyAttribute(name: 'John', age: 30)]

    public string $name;



    #[MyAttribute(name: 'Jane', age: 25)]

    public string $email;

}



$user = new User();

$reflectionClass = new ReflectionClass($user);

$attributes = $reflectionClass->getAttributes();



foreach ($attributes as $attribute) {

    $attributeName = $attribute->getName();

    $attributeValue = $attribute->getValue();



    if ($attributeName === MyAttribute::class) {

        $myAttribute = $attributeValue;

        echo "Name: {$myAttribute->name}
";

        echo "Age: {$myAttribute->age}
";

    }

}



위의 예제에서 `ReflectionClass`를 사용하여 `User` 클래스의 Attribute를 접근했습니다. Attribute의 이름과 값이 `MyAttribute` 인지 확인하고, `MyAttribute`의 `name`과 `age` 프로퍼티를 출력했습니다.

결론

Attribute는 PHP에서 클래스, 메소드, 프로퍼티에 대한 추가적인 정보를 제공할 수 있습니다. `__construct` 메소드를 사용하여 Attribute를 초기화할 수 있고, Reflection API를 사용하여 Attribute를 접근할 수 있습니다. Attribute를 사용하여 클래스, 메소드, 프로퍼티에 대한 정보를 얻을 수 있습니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 8,985건 / 594 페이지

검색

게시물 검색