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 underline 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) {

Note that in PHP 7.2 and older, instanceOf operator requires an object. If you need to make your code function across PHP versions older than 7.3 through PHP 8.0, you will need an additional is_object() check:

- if (is_resource($image)) {
+ if (is_resource($image) || (is_object($image) && $image instanceOf \GdImage)) {

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.

Backwards Compatibility Impact

GD extension's resource to object migration is quite transparent. It will not be necessary to polyfill the new GdImageclass 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.