PHP Resource Data Type

PHP includes various data types such as integer, double, string like many other programming languages. In this tutorial, we are going to see PHP resource data types.

But, unlike other data types, it is acting as a reference or an identifier to access resource data. For example, when we attempt to access the database or a file resource, we can have a resource identifier. This identifier will be used to hook the resource to access data.

Examples of Getting Resource Data

The following code shows how to get the database resource identifier by requesting the MySQL connection. In this code, the database information is specified for the mysqli_connect() and it returns the MySQL connection object as a resource identifier.

<?php
$conn = mysqli_connect(localhost, "root", "admin", "animals");
?>

While working with files, we need to get the file resource identifier. with reference to this identifier, we can perform the write, append and more file manipulation operations. The following PHP code is used to create a file resource object reference.

<?php
$fp = fopen("index.php", 'r');
?>

After finishing all the operations with the resource data, the connection or the hook we created with the external resources will be cleared. The following PHP functions are used to clear the resource object reference created for the database and the file resource.

<?php
mysqli_close($conn);
fclose($fp);
?>
Photo of Vincy, PHP developer
Written by Vincy Last updated: July 2, 2022
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

2 Comments on "PHP Resource Data Type"

Leave a Reply

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

Explore topics
Need PHP help?