What is the typed property for Resource

chriss :

What is the right type for typed properties when i want to store a resource (like a ftp-Stream or ftp-Buffer)?

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

There is no type like Resource. So the following wont work:

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

cause php think this is a class called Resource.

iainn :

Short answer:

You can't. Sorry.

Some background:

There's an RFC here discussing the gap, but it hasn't moved since 2015: https://wiki.php.net/rfc/resource_typehint

The original RFC for scalar type hints specified that

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).

There's a comment on bug 71518 making the point that type-hinting for a resource really isn't very useful, since you'd still be able to pass in a file handle, or a GD resource, or a CURL handle, none of which do remotely the same thing. The bug itself has been suspended, so it doesn't look like this is going to be addressed any time soon.

A user-land compromise could be to write a thin object-wrapper around whichever resource type you need, and type-hint against that class instead. You still won't get typed property support for the resource on your new object, but it makes the issue less visible to the rest of your application.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=345920&siteId=1
Recommended