【问题标题】:How to test if Callable parameter will return a string with Reflection?如何测试 Callable 参数是否会返回带有反射的字符串?
【发布时间】:2018-09-29 00:40:29
【问题描述】:

我有一个需要Callable 参数的函数。我想确定这个可调用对象返回一个字符串,如果没有,应该抛出异常。

我试图搜索这个,但没有运气。 PHP 反射 API 是否提供这样的功能?我不想运行该方法并查看它是否真的返回一个字符串。

我需要的示例:

class MyClass
{
    protected static $overrider = null;

    public static function setOverrider(Callable $callback)
    {
        // Pseudo code start
        if (!$callback returns string) {
            throw new \Exception('Wasnt a string!');
        }
        // Pseudo code end     

        self::$overrider = $callback;
    }
}

【问题讨论】:

  • 我假设您使用的是 PHP 7+,对吧?因为 PHP wiki.php.net/rfc/return_types(提案)php.net/manual/en/…
  • 是的,但我不确定这有什么关系。我添加了一个我需要的例子。谢谢!

标签: php reflection callback php-7 callable


【解决方案1】:

也许你需要这样的东西:

class MyClass
{
    protected static $overrider = null;

    public static function setOverrider(Callable $callback)
    {
        $reflection = new ReflectionFunction($callback);
        if ('string' != $reflection->getReturnType()) {
            throw new \Exception('Wasnt a string!');
        }  

        self::$overrider = $callback;
    }
}

所以,正如我之前在 cmets 中提到的:您需要声明可调用对象的返回类型(即 PHP7+ feature)。这是必须的,否则将无法正常工作

像这样:

function my_function(): string
{
    return 'hello';
}

如果你喜欢匿名函数,也可以这样(Closure):

$my_callable = function(): string {
    return 'hello';
}

就这么简单: 如果你不先告诉解释器应该返回什么函数,解释器就无法知道函数的返回数据类型而不调用它。

【讨论】:

  • 没关系,我很抱歉。这不是我要找的。​​span>
  • 我不会在我的项目中强制执行严格的类型。我假设我可以在不调用 callable 的情况下获取返回类型。
  • 我真的认为我的回答完全符合你的问题。您想在不调用的情况下知道“可调用”的返回类型,对吗?
  • 是的,它适合,因此接受。感谢您的宝贵时间。
  • 就这么简单:如果你不先告诉解释器应该返回什么函数,解释器就无法知道函数的返回数据类型而不调用它。
猜你喜欢
  • 2015-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 2016-07-05
  • 2021-06-22
相关资源
最近更新 更多