Php 我可以为递归迭代器结果对象提供typehint吗?
在php项目中,我可以通过以下方式获得所有文件的列表:Php 我可以为递归迭代器结果对象提供typehint吗?,php,iterator,phpstorm,return-type,phpdoc,Php,Iterator,Phpstorm,Return Type,Phpdoc,在php项目中,我可以通过以下方式获得所有文件的列表: /** * @param string $dirPath * * @return RecursiveIteratorIterator */ private static function getFiles(string $dirPath): RecursiveIteratorIterator { return new RecursiveIteratorItera
/**
* @param string $dirPath
*
* @return RecursiveIteratorIterator
*/
private static function getFiles(string $dirPath): RecursiveIteratorIterator
{
return new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dirPath, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
}
我可以通过以下方式使用它:
$files = self::getFiles($dirPath);
然而,当我使用它时,我发现自己在动态地注释类型:
foreach ($files as $fileinfo) {
/**
* @var SplFileInfo $fileinfo
*/
$rm = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
$rm($fileinfo->getRealPath());
}
是否有一种方法可以在getFiles
-方法级别对类型进行注释
使用递归迭代器会使任何类型提示混合,例如,对于当前:
/**
* Access the current element value
* @link https://php.net/manual/en/recursiveiteratoriterator.current.php
* @return mixed The current elements value.
*/
public function current() { }
另外,我想保留一个严格的返回类型,所以我不想使用:
/**
* @param string $dirPath
*
* @return RecursiveIteratorIterator|SplFileInfo[]
*/
private static function getFiles(string $dirPath) {
...
}
因为我不想谎称结果是数组。它不是,它是一个迭代器
/可遍历的
,它生成SplFileInfo
对象
充其量是一种通用的方法,但也只有phpstorm解决方案就足够了
我尝试使用严格返回类型
iterable
和phpdoc commentiterable
,但这不起作用。您试图准确地注释什么对象&在代码中哪里需要它?如果只是foreach中的$fileinfo
用法,恐怕没有其他选择。