Get Resource ID using get_resource_id in PHP 8.0

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 a unique ID. In versions prior to PHP 8.0, to get the resource ID, we need to cast a resource to int.

<?php

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

Since PHP 8.0, we can use the get_resource_id function to get ID for the given resource. This function ensures a type of 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

Cancel reply

Your email address will not be published.