为了账号安全,请及时绑定邮箱和手机立即绑定

类型提示闭包参数

类型提示闭包参数

PHP
MMMHUHU 2021-09-05 20:49:31
使用 PHP 中的类型提示是否可以对闭包的参数进行类型提示?例如function some_function(\Closure<int> $closure) {    $closure(3);}// This would throw an exceptionsome_function(function(string $value) {    echo $value;});// This would work.some_function(function(int $value) {    echo $value;});
查看完整描述

1 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

不是原生的。您需要手动使用反射。


<?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


查看完整回答
反对 回复 2021-09-05
  • 1 回答
  • 0 关注
  • 145 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信