如何在 PHP 函数中添加“流资源”返回类型

Keu*_*cht 5 php file function return-type

我正在尝试向正在获取资源类型文件的函数添加返回类型,但我无法弄清楚要添加什么返回类型?我收到一个错误,我的返回是一个资源,并且应该是一个资源,这让我很困惑:P

这是我的函数(此函数中发生了更多事情来创建文件路径,但我将其省略,因为它不相关。

private function getMappingExportFile(JobParameters $jobParameters): \resource
{
    return fopen($filePath,"r");
}
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误

::getMappingExportFile() must be an instance of resource, resource returned 
Run Code Online (Sandbox Code Playgroud)

如果删除返回类型,一切都会正常,但我更喜欢使我的代码更加严格。

Pep*_*ier 0

As of March 2023 this still seems impossible. As @Keutelvocht commented, more info on why this is, can be found in PHP 7 and strict "resource" types


However, you can still (softly) typehint this using a docblock above your function.

/**
 * @param JobParameters $jobParameters
 * @return resource
 */
private function getMappingExportFile(JobParameters $jobParameters)
{
    return fopen($filePath,"r");
}
Run Code Online (Sandbox Code Playgroud)