PHP 8.0: New get_resource_id
function
PHP resources, such as Curl handlers, open files, database connections, can be cast to int
. PHP 8 adds a new get_resource_id
function that is essentially a (int) $resource
cast to make it easier to retrieve the resource ID.
The advantage of the new get_resource_id
function is the type safety, that arguments and return type are checked to be a resource
and an int
.
get_resource_id()
Function synopsis
function get_resource_id($res): int {}
Note that PHP does not have a resource
type that can be enforced yet.
Polyfill
function get_resource_id($res): int {
if (!\is_resource($res) && null === @get_resource_type($res)) {
throw new \TypeError(sprintf('Argument 1 passed to get_resource_id() must be of the type resource, %s given', get_debug_type($res)));
}
return (int) $res;
}
From Symfony/Polyfill
package. Supports PHP 7.0 and later.
Backwards Compatibility Impact
get_resource_id
is a new function, and it can be easily polyfilled in previous PHP versions. Unless you have declared a function with exact same name in the global namespace, there should not be any problems.