我想检查可调用对象的返回类型是否是另一种类型的实例。例如,假设我有:
Pigeon
扩展了 Animal
。addSupplier()
接受一个 callable
参数并期望返回
输入 Animal
。addSupplier()
的调用传递一个返回 Pigeon
的闭包。这是代码示例:
namespace Foo\Bar;
class Animal {
// ...
}
class Pigeon extends Animal {
// ...
}
class Suppliers {
public static function test() {
self::addSupplier(fn() => new Pigeon());
}
public static function addSupplier(callable $callable) {
$reflection = new ReflectionFunction($callable);
$type = $reflection->getReturnType();
if($type->isInstance('\Foo\Bar\Animal')) { // Pseudocode
// It's an animal!
} else
throw new InvalidArgumentException("Callable must return an animal!");
}
}
有没有办法让
addSupplier
检查可调用参数的返回类型以确保它是Animal
的实例?
如当前所写,您的可调用对象最终将返回一个
Pigeon
实例,但不限于这样做。如果添加返回类型提示,就可以实现您的要求。看看这个修改:
<?php
namespace Foo\Bar;
class Animal {
// ...
}
class Pigeon extends Animal {
// ...
}
class Suppliers {
public static function test() {
self::addSupplier(fn(): Pigeon => new Pigeon());
}
public static function addSupplier(callable $callable) {
$reflection = new \ReflectionFunction($callable);
$type = $reflection->getReturnType();
if($type && (new \ReflectionClass($type->getName()))->isSubclassOf('\Foo\Bar\Animal')) {
print("It's an animal!");
} else
throw new \InvalidArgumentException("Callable must return an animal!");
}
}
Suppliers::test();