类型提示关闭参数 [英] Type-hint closure parameters

查看:48
本文介绍了类型提示关闭参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP中的类型提示是否可以类型提示闭包的参数?

With type-hinting in PHP is it possible to type-hint the parameters of a closure?

例如

function some_function(\Closure<int> $closure) {
    $closure(3);
}

// This would throw an exception
some_function(function(string $value) {
    echo $value;
});

// This would work.
some_function(function(int $value) {
    echo $value;
});


推荐答案

不是本地的。您需要手动使用反射

Not natively. You would need to manually make use of reflection.

<?php
function some_function(\Closure $closure) {

    $reflection = new ReflectionFunction($closure);
    $parameters = $reflection->getParameters();
    if(!isset($parameters[0]))
    {
        // I'm lazy but you should program this to throw a fatal exception
        echo 'some_function() expects parameter one\'s closure to expect at least one parameter'.PHP_EOL;
    }
    elseif($parameters[0]->getType().'' !== 'int') // I'm sure there is a more elegant way to achieve this...
    {
        // I'm lazy but you should program this to throw a fatal exception
        echo 'closure\'s first param should be an int'.PHP_EOL;
    }
    else
    {
        $closure(3);
    }
}

// Does not throw an exception
some_function(function(int $value) {
    var_dump($value);
});

// This throws an exception
some_function(function() {
    var_dump($value);
});

// This throws an exception
some_function(function(string $value) {
    var_dump($value);
});

产品:

int(3)
some_function() expects parameter one's closure to expect at least one parameter
closure's first param should be an int

另请参见推导PHP闭包参数

这篇关于类型提示关闭参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆