PHP 8.1: finfo Extension: file_info resource are migrated to existing finfo objects

Version8.1
TypeChange

finfo extension has gone through the Resource to Object Migration, that the procedural API in the finfo extension transparently returns and accepts finfo class instances.


Resource to Object Migration PHP is gradually phasing out all resource types with class objects, and this migration is one step of the Resource to Object Migration plan.


In PHP 8.1, the following functions from finfo extension return and accept finfo class instances instead of resource objects with type file_info.

finfo class

finfo class already exists in all PHP versions (PHP >= 5.3), but prior to PHP 8.1, the procedural-style finfo_* functions returned/accepted resources instead. From PHP 8.1, it is even possible to interchange the procedural return values with Object-Oriented style objects.

The finfo class continues to function with same semantics as before, and there are no changes in finfo class.

Destructing finfo class instances

The finfo_close function is still available, and is not deprecated.

Calling finfo_close no longer has any effect. It is possible to continue to use a closed resource, which was not possible prior to PHP 8.0.

$f = finfo_open();
finfo_close($f);
finfo_file($f, 'test.txt'); // Allowed in PHP 8.1, but not prior.

Prior to PHP 8.1, using a closed resource was not allowed, and the snippet above would have resulted in an error:

TypeError: finfo_file(): supplied resource is not a valid file_info resource

In PHP 8.1 and later, because the finfo_close function has no effect, this pattern does not result in an error.

finfo objects will be automatically destroyed when they fall out of scope. It is possible to destroy them explicitly as well:

unset($finfo);

Backwards Compatibility Impact

Similar to other Resource to Object Migration changes, the use of is_resource function on return value of finfo_open no longer returns true. It returns false instead.

To accept external finfo instances, it is now necessary to account for finfo class instances as well for compatibility with older PHP versions:

- is_resource($finfo)
+ is_resource($finfo) || $finfo instanceof finfo

Upon resource/object instantiation, a check against !== false is sufficient as well:

$finfo = finfo_open();
- is_resource($finfo);
+ $finfo !== false 

Alternately, a full-on migration to the OOP-style finfo class might be an easier upgrade, as it has no effective changes at all.

Apart from the is_resource function, the rest of the finfo API remains opaque, because all functions that previously accepted a file_info resource now accept finfo class objects.


Implementation