Get Resource ID using get_resource_id in PHP 8.0

Resource is a type of variable that contains a reference to an external resource. It can be database connection, file handle, cURL handle, etc.

Each resource is identified by unique ID. In versions prior to PHP 8.0, in order to get the resource ID we need to cast an resource to int.

<?php

$resource = fopen('test.txt', 'rb');
$id = (int) $resource;

Since PHP 8.0, we can use get_resource_id function to get ID for the given resource. This function ensures a type safety. It means that resource ID is always returned as int.

<?php

$resource = fopen('test.txt', 'rb');
$id = get_resource_id($resource);

Leave a Comment

Your email address will not be published. Required fields are marked *