How to get resource ID using get_resource_id() function in PHP and PHP 8?


The resource is a type of variable that holds a reference to an external resource. The resource can be a filehandle, a database connection, or a URL handle. Every resource is identified by a unique id. In the previous versions of PHP, we needed to cast a resource to int to get the resource id.

Example: get_recource_id using int.

<?php
   $x = fopen('test.txt', 'rb');
   $id = (int) $x;
   print_r($id);
?>

Output

1

In PHP 8, the get_resource_id() function always returns an int. It is used to get the ID for a given resource. This function always guarantees type safety.

Example: Using get_recource_id in PHP 8.

<?php
   $x = fopen('test.txt', 'rb');
   echo get_resource_id($x);
?>

Output

1

Updated on: 01-Apr-2021

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements