我可以检查 ReflectionType 是否是另一种类型的实例吗?

问题描述 投票:0回答:1

我想检查可调用对象的返回类型是否是另一种类型的实例。例如,假设我有:

  1. 一个类
    Pigeon
    扩展了
    Animal
  2. 一个函数
    addSupplier()
    接受一个
    callable
    参数并期望返回 输入
    Animal
  3. 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
的实例?

php types reflection php-7 anonymous-function
1个回答
0
投票

如当前所写,您的可调用对象最终将返回一个

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();
© www.soinside.com 2019 - 2024. All rights reserved.