PHP 8.1: IMAP: imap resources are IMAP\Connection class objects

Version8.1
TypeChange

In PHP 8.1, IMAP connection resources from the imap extension are migrated to class objects.

Prior to PHP 8.1, imap_open() function returned a resource object of type imap. From PHP 8.1 and later, it returns an IMAP\Connection class instance instead.

All functions that previously accepted resources accept the new type as well.

IMAP\Connection Class Synopsis

namespace IMAP;
final class Connection {}

In line with other resource to object migration semantics, the new IMAP\Connection class is declared final as well, to minimize the potential backwards-compatibility breaks when PHP modifies the implementation details of the class.

imap_open function is still used to create IMAP\Connection class instances, and instantiating with new IMAP\Connection() construct is not allowed:

new IMAP\Connection();
Cannot directly construct IMAP\Connection, use imap_open() instead

Because the IMAP\Connection class is declared final, it is not allowed to extend it.

class Foo extends IMAP\Connection {}
PHP Fatal error:  Class Foo may not inherit from final class (IMAP\Connection) in ... on line ...

is_resource checks

All resource to object migrated class objects no longer return true for is_resource function, and any code that used is_resource function to check the validity of an IMAP connection resource will cause problems in PHP 8.1 and later.

In all PHP versions, imap_open function returns false in case it failed to create an IMAP resource. This is still the case for PHP 8.1 and later as well.

Existing code that needs to check the validity of a given variable for an IMAP connection needs to account for IMAP\Connection class object return values in PHP 8.1 and later.

- is_resource($imap_connection)
+ is_resource($imap_connection) || $imap_connection instanceof \IMAP\Connection

Alternately, a check against false might be more appropriate and more readable, and works across all PHP versions too.

- is_resource($imap_connection)
+ $imap_connection !== false

Closing IMAP\Connection resources

IMAP connections are automatically closed when the IMAP\Connection is no longer referenced (i.e fall out of scope), or when explicitly destroyed with unset($connection).

imap_close function, that was used to close imap resources is still available and functional. Attempting to use a closed IMAP\Connection object results in a \ValueError exception.

ValueError: IMAP\Connection is already closed

Backwards Compatibility Impact

Following other resource to object migrations, IMAP extension seamless upgrades return and accepted parameter types to the new object-based resources.

is_resource function now returns false instead of the previous true return value for IMAP connection objects. This might be a backwards-compatibility issue if the IMAP connection resources are checked with that function. See is_resource checks section for possible workarounds

Related Changes


Implementation