PHP Resource Data Type

by Vincy. Last modified on July 2nd, 2022.

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);
?>
Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP Resource Data Type”

Leave a Reply

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

↑ Back to Top

Share this page