资源的类型 属性 是什么

What is the typed property for Resource

当我想存储资源(如 ftp-Stream 或 ftp-Buffer)时,类型属性的正确类型是什么?

/**
 * @var Resource|null
 */
private $__ftp_connection = null;

没有 Resource 这样的类型。所以以下不会工作:

/**
 * @var Resource|null
 */
private ?Resource $__ftp_connection = null;

因为 php 认为这是一个 class 称为资源。

简答:

你不能。对不起。

一些背景:

这里有一个 RFC 讨论了这个差距,但它自 2015 年以来就没有动过:https://wiki.php.net/rfc/resource_typehint

original RFC for scalar type hints指定

No type declaration for resources is added, as this would prevent moving from resources to objects for existing extensions, which some have already done (e.g. GMP).

bug 71518 上有一条评论指出,资源的类型提示实际上不是很有用,因为您仍然可以传入文件句柄或 GD 资源,或 CURL 句柄,其中 none 远程执行相同的操作。该错误本身已被暂停,因此看起来不会很快得到解决。

用户空间的妥协可能是围绕您需要的任何资源类型编写一个薄的对象包装器,然后针对该 class 进行类型提示。您仍然不会在新对象上获得对资源的类型化 属性 支持,但这会使该问题对应用程序的其余部分不那么明显。