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

PHPServer Side ProgrammingProgramming

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
raja
Published on 01-Apr-2021 06:50:28
Advertisements