PHP 8.0: GdImage
class objects replace GD image resources
From PHP 8.0 and forward, GD extension uses \GdImage
class objects instead of resource
s for its underlying data structures.
This is similar to Curl extension using \CurlHandle
objects as opposed to resource
in PHP 8.0.
\GdImage
class
final class GdImage{
}
\GdImage
is declared in global namespace.- Declared
final
. - Has no methods.
- Cannot be instantiated with
new \GdImage()
. - Cannot be cloned with
clone $image
. - Cannot be serialized.
GD functions return and accept \GdImage
objects instead of resource
All GD functions that accepted resource
values parameters prior to PHP 8.0 will now accept \GdImage
objects. Similarly, their return values will be \GdImage
objects instead of resource
.
is_resource()
calls
Note that all functions in GD extension now returns and expects \GdImage
objects instead of resource
objects. Unless you explicitly call is_resource()
function on return values of GD functions (such as imagecreatefromjpeg()
and imagecreate()
), this change will be completely trouble-free.
If you are calling is_resource
, you will now need to account for the \GdImage
object return type too.
- if (is_resource($image)) {
+ if (is_resource($image) || $image instanceof \GdImage) {
A previous version of this post recommended to use
is_object
beforeinstanceof
calls on PHP versions prior to 7.2. It is not necessary to useis_object
calls withinstanceof
operator as long as they are not literals, as shown in the example above.
imagedestroy()
is no-op
imagedestroy()
function is still available in PHP 8.0, but it does nothing. Memory and other resources will be freed when the \GdImage
object is removed either with an explicit unset()
call or when it falls out of scope.
Gd font
The remaining GD font
resource is migrated to a class object in PHP 8.1: Font identifiers are \GdFont
class objects.
Backwards Compatibility Impact
GD extension's resource
to object
migration is quite transparent. It will not be necessary to polyfill the new GdImage
class because the internal nature of this change.
Existing code that uses is_resource()
will now need either change to check the class name of the object to support PHP 8.0.