类型提示闭包参数

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


例如


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;

});


MMMHUHU
浏览 146回答 1
1回答

蛊毒传说

不是原生的。您需要手动使用反射。<?phpfunction some_function(\Closure $closure) {&nbsp; &nbsp; $reflection = new ReflectionFunction($closure);&nbsp; &nbsp; $parameters = $reflection->getParameters();&nbsp; &nbsp; if(!isset($parameters[0]))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // I'm lazy but you should program this to throw a fatal exception&nbsp; &nbsp; &nbsp; &nbsp; echo 'some_function() expects parameter one\'s closure to expect at least one parameter'.PHP_EOL;&nbsp; &nbsp; }&nbsp; &nbsp; elseif($parameters[0]->getType().'' !== 'int') // I'm sure there is a more elegant way to achieve this...&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // I'm lazy but you should program this to throw a fatal exception&nbsp; &nbsp; &nbsp; &nbsp; echo 'closure\'s first param should be an int'.PHP_EOL;&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $closure(3);&nbsp; &nbsp; }}// Does not throw an exceptionsome_function(function(int $value) {&nbsp; &nbsp; var_dump($value);});// This throws an exceptionsome_function(function() {&nbsp; &nbsp; var_dump($value);});// This throws an exceptionsome_function(function(string $value) {&nbsp; &nbsp; var_dump($value);});产生:int(3)some_function() expects parameter one's closure to expect at least one parameterclosure's first param should be an int
打开App,查看更多内容
随时随地看视频慕课网APP