PHP 8.1: FTP Extension: Connection resources are FTP\Connection class objects

Version8.1
TypeChange

FTP connection resources from the ftp extension are migrated to class objects in PHP 8.1.

Prior to PHP 8.1, FTP connections created with ftp_connect(), and ftp_ssl_connect() functions returned a resource of type ftp. In PHP 8.1 and later, those functions return a FTP\Connection class instance instead.

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

FTP\Connection Class Synopsis

namespace FTP;
final class Connection {}

Similar to other resource to object migrations, the new FTP\Connection class is declared final to prevent them from extended (and reduce potential backwards-compatibility issues if PHP core changes the methods of the FTP\Connection class).

Instantiating a new instance of FTP\Connection is not allowed, and results in an \Error Exception.

new FTP\Connection();
Cannot directly construct FTP\Connection, use ftp_connect() or ftp_ssl_connect() instead

is_resource checks

User-land PHP code that work with ftp resources sometimes check for the validity of the resource object with is_resource function.

This was not necessary because ftp_connect and ftp_ssl_connect functions return false on error. This pattern is maintained in PHP 8.1 too.

To check if creation of an FTP resource was successful, a simple check for false is cross-version compatible, and is just as accurate as a is_resource check.

Existing code that relied on is_resource function now needs to account for the new FTP\Connection class objects in PHP 8.1.

- is_resource($ftp_connection)
+ is_resource($ftp_connection) || $ftp_connection instanceof \FTP\Connection

Alternately, a check against false might be more appropriate and more readable.

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

Destroying FTP\Connection objects

Destroying an FTP\Connection object, or leaving it for the garbage collector to clean up will automatically close the FTP connection.

It is still possible to explicitly close the FTP connection with ftp_close function. This function is not deprecated and is still functional.

Attempting to use a closed FTP connection object will throw a ValueError exception.

ValueError: FTP\Connection is already closed

Backwards Compatibility Impact

Similar to other resource to object migrations, FTP 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 FTP connection objects. This might be a backwards-compatibility issue if the FTP connection resources are checked with that function.


Implementation