라이브러리

[PHP] ReflectionClassConstant::hasType - 클래스 상수에 유형이 있는지 확인합니다.




ReflectionClassConstant::hasType


PHP 8.1 버전부터 ReflectionClassConstant 클래스가 추가되었으며, 이 클래스는 클래스의 상수에 대한 정보를 제공합니다. ReflectionClassConstant::hasType 메소드는 특정 타입을 가진 상수가 있는지 확인하는 메소드입니다.

사용 예제


#hostingforum.kr
php

class MyClass {

    const MY_CONSTANT = 'hello';

    const MY_CONSTANT_INT = 123;

    const MY_CONSTANT_FLOAT = 123.45;

}



$reflectionClass = new ReflectionClass(MyClass::class);

$reflectionConstant = $reflectionClass->getConstant('MY_CONSTANT');



echo $reflectionConstant->getName() . "
"; // MY_CONSTANT

echo $reflectionConstant->getValue() . "
"; // hello

echo $reflectionConstant->getType() . "
"; // string



echo $reflectionClass->hasType('MY_CONSTANT', 'string') ? 'true' : 'false'; // true

echo $reflectionClass->hasType('MY_CONSTANT', 'int') ? 'true' : 'false'; // false



echo $reflectionClass->hasType('MY_CONSTANT_INT', 'int') ? 'true' : 'false'; // true

echo $reflectionClass->hasType('MY_CONSTANT_INT', 'string') ? 'true' : 'false'; // false



echo $reflectionClass->hasType('MY_CONSTANT_FLOAT', 'float') ? 'true' : 'false'; // true

echo $reflectionClass->hasType('MY_CONSTANT_FLOAT', 'int') ? 'true' : 'false'; // false



설명


- `ReflectionClassConstant::hasType` 메소드는 첫 번째 인자로 클래스의 상수 이름을, 두 번째 인자로 타입을 받습니다.
- 이 메소드는 첫 번째 인자로 받은 상수가 두 번째 인자로 받은 타입을 가진 상수인지 확인하고, true 또는 false를 반환합니다.
- 예제에서 `MY_CONSTANT` 상수는 string 타입을 가진 상수이므로 `hasType('MY_CONSTANT', 'string')`은 true를 반환합니다.
- 예제에서 `MY_CONSTANT_INT` 상수는 int 타입을 가진 상수이므로 `hasType('MY_CONSTANT_INT', 'int')`은 true를 반환합니다.
- 예제에서 `MY_CONSTANT_FLOAT` 상수는 float 타입을 가진 상수이므로 `hasType('MY_CONSTANT_FLOAT', 'float')`은 true를 반환합니다.

참고


- `ReflectionClassConstant` 클래스는 PHP 8.1 버전부터 사용할 수 있습니다.
- `hasType` 메소드는 클래스의 상수에 대한 정보를 제공하는 `ReflectionClassConstant` 클래스의 메소드입니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 287 페이지

검색

게시물 검색