PHP 8.1: GD Extension: Font identifiers are GdFont class objects

Version8.1
TypeChange

Prior to PHP 8.1, the imageloadfont function from GD extension returned a font-identifier resource ID as an integer. In PHP 8.1 and later, the resource ID is migrated to a GdFont class instance.

All functions that previously accepted a resource ID from imageloadfont function now accept the new GdFont class objects, making this an opaque change.


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.


imageloadfont function return value is changed from int to GdImage. This is different from other resource to object migrations that replaced a resource with a class instance.

gd resource for primitive GD images was migrated to GdImage class instances in PHP 8.0: GdImage class objects replace GD image resources

GdFont class synopsis

final class GdFont {}

Directly instantiating a GdFont instance is not allowed, and it is still required to use the imageloadfont:

$font = new GdFont();
PHP Error:  You cannot initialize a GdFont object except through helper functions in ... on line ...

GdFont class is also declared final, to prevent it from being extended with child classes, to reduce potential backwards-compatibility issues if the GdFont class structure changes in the future.

Backwards Compatibility Impact

Prior to this change in PHP 8.1, the GD Font resources were int values. All code with parameter/return/property type with this assumption now needs to accommodate GdFont class instances.

In PHP 8.0, Union Types can enforce this requirement.

- function addFont(int $gdfont){}
+ function addFont(int|GdFont $gdfont) {}

imageloadfont function continues to return false in case the font file could not be loaded, and a check against false value might be more readable and appropriate:

$font = imageloadfont($file);
- if (is_int($font)) {
+ if ($font !== false) {
 // 
}

Implementation