I want to check if a callable’s return type is an instance of another type. For example, let’s say I a have:
- A class
Pigeon
which extendsAnimal
. - A function
addSupplier()
which takes acallable
argument and expects the return
type to beAnimal
. - A call to
addSupplier()
which passes a closure that returns aPigeon
.
Here is the example in code:
namespace FooBar;
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('FooBarAnimal')) { // Pseudocode
// It's an animal!
} else
throw new InvalidArgumentException("Callable must return an animal!");
}
}
Is there a way that addSupplier
can check the the return type of the callable parameter to ensure that it will be an instance of Animal
?