ReflectionUnionType::getTypes
(PHP 8)
ReflectionUnionType::getTypes — 返回联合类型中包含的类型
参数
此函数没有参数。
返回值
包含 ReflectionType 对象的数组。
示例
示例 #1 ReflectionUnionType::getTypes() 示例
<?php
function someFunction(int|float $number) {}
$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParam = $reflectionFunc->getParameters()[0];
var_dump($reflectionParam->getType()->getTypes());
以上示例的输出类似于:
array(2) { [0] => class ReflectionNamedType#4(0) { } [1] => class ReflectionNamedType#5(0) { } }
参见
- ReflectionType::allowsNull() - Checks if null is allowed
- ReflectionParameter::getType() - Gets a parameter's type
+添加备注
用户贡献的备注 2 notes
baptiste at pillot dot fr ¶
1 year ago
Sorting :
Contrary to what one might expect, the returned array of ReflectionType objects will not be sorted in the same order than the types declared into the source code.
- Classes, interfaces, traits, iterable (replaced by Traversable), ReflectionIntersectionType objects, parent and self: these types will be returned first, in the order in which they were declared.
- static and all built-in types (iterable replaced by array) will come next. They will always be returned in this order: static, callable, array, string, int, float, bool (or false or true), null.
Notice that when used into an union type, iterable is an alias for Traversable|array. ReflectionUnionType::getTypes will return these both ReflectionNamedType objects, instead of a single one named 'iterable'.
Example :
<?php
class PC {}
class C extends PC {
function f(): null|bool|float|int|parent|PC|string|iterable|(ReflectionClass&ReflectionProperty)|callable|static|self|C {}
}
echo join(', ', array_map(
function($t) { return ($t instanceof ReflectionIntersectionType) ? '<intersection>' : $t->getName(); },
(new ReflectionMethod('C', 'f'))->getReturnType()->getTypes()
)) . "\n";
?>
Will display :
parent, PC, Traversable, <intersection>, self, C, static, callable, array, string, int, float, bool, null
Try it: https://onlinephp.io/c/777c6
baptiste at pillot dot fr ¶
1 year ago
ReflectionUnionType::getTypes can return an array of ReflectionNamedType and/or ReflectionIntersectionType objects only.
备份地址:http://www.lvesu.com/blog/php/reflectionuniontype.gettypes.php