通过 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;
});
不是原生的。您需要手动使用反射 https://php.net/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 闭包参数 https://stackoverflow.com/q/19198804/2191572
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)