Understanding the Shift from Resources to Objects

The PHP language has always had an uneasy relationship with resources. Resources represent a connection to an external system, such as a file handle or a connection to a remote web service using the client URL (cURL) extension. One big problem with resources, however, is that they defy attempts at data typing. There’s no way to distinguish a file handle from a cURL connection—they’re both identified as resources.

In PHP 8, a major effort has taken place to move away from resources and replace them with objects. One of the earliest examples of this trend prior to PHP 8 is the PDO class. When we create a PDO instance, it automatically creates a database connection. Starting with PHP 8, many functions that previously produced a resource now produce an object instance instead. Let’s start our discussion by having a look at extension functions that now produce objects rather than resources.

PHP 8 extension resource-to-object migration

It’s important for us to be aware of which functions in PHP 8 now produce objects instead of resources. The good news is that the extension functions have also been rewritten to accommodate an object as an argument rather than a resource. The bad news is that there is a potential backwards-compatible code break where we initialize the resource (now object) and test for success using the is_resource() function.

The following table summarizes the functions that formerly returned resources but now return object instances:

Get hands-on with 1400+ tech skills courses.