English | 简体中文 | 繁體中文
查询

ReflectionUnionType::getTypes()函数—用法及示例

「 获取联合类型中的所有类型 」


函数名称:ReflectionUnionType::getTypes()

适用版本:PHP 8.1.0 及以上版本

函数描述:ReflectionUnionType::getTypes() 方法用于获取联合类型中的所有类型。

用法示例:

<?php
class MyClass {
    public int|string $property;
}

$reflectionClass = new ReflectionClass('MyClass');
$property = $reflectionClass->getProperty('property');
$type = $property->getType();

if ($type instanceof ReflectionUnionType) {
    $types = $type->getTypes();
    
    foreach ($types as $type) {
        echo $type->getName() . "\n";
    }
}
?>

在上面的示例中,我们定义了一个名为 MyClass 的类,其中的 $property 属性被声明为 int|string 的联合类型。通过使用 ReflectionClassReflectionProperty 可以获取到属性的类型,然后通过 getType() 方法获取到类型的反射对象。

接下来,我们使用 instanceof 操作符检查类型是否为 ReflectionUnionType 的实例。如果是联合类型,则可以使用 getTypes() 方法获取到联合类型中的所有类型。

在循环中,我们遍历了所有的类型,并使用 getName() 方法获取到类型的名称,最后将类型名称打印输出。

以上示例将输出:

int
string

这表明 $property 属性的类型是一个由 intstring 构成的联合类型。

补充纠错
热门PHP函数
分享链接