Definition and Usage
In PHP, Resource is a special data type that refers to any external resource. A resource variable acts as a reference to external source of data such as stream, file, database etc. PHP uses relevent functions to create these resources. For example, fopen() function opens a disk file and its reference is stored in a resource variable.
PHP's Zend engine uses reference conting system. As a result, a resource with zero reference count is destroyed automatically by garbage collector. Hence, memory used by resource data type need not be freed manually.
Various types of resources can be handled in a PHP script, with the help of coresponding functions. Following table shows a select list −
Resource Type Name | Created By | Destroyed By | Definition |
bzip2 | bzopen() | bzclose() | Bzip2 file |
curl | curl_init() | curl_close() | Curl session |
ftp | ftp_connect(), | ftp_close() | FTP stream |
mssql link | mssql_connect() | mssql_close() | Link to Microsoft SQL Server database |
mysql link | mysql_connect() | mysql_close() | Link to MySQL database |
mysql result | mysql_db_query(), | mysql_free_result() | MySQL result |
oci8 connection | oci_connect() | oci_close() | Connection to Oracle Database |
ODBC link | odbc_connect() | odbc_close() | Link to ODBC database |
pdf document | pdf_new() | pdf_close() | PDF document |
stream | opendir() | closedir() | Dir handle |
stream | fopen(), tmpfile() | fclose() | File handle |
socket | | fclose() | Socket handle |
xml | xml_parser_create(), | xml_parser_free() | XML parser |
zlib | gzopen() | gzclose() | gz-compressed file |
zlib.deflate | deflate_init() | None() | incremental deflate context |
zlib.inflate | inflate_init() | None() | incremental inflate context |
In this context, PHP has get_resource_type() function that returns resource type of a variable.
Syntax
To declare an object of a class we need to use new statement
get_resource_type ( resource $handle ) : string
where $handle is the resource variable whose type is to be obtained. This function returns a string corresponding to resource type
Following example shows resource type of a disk file
Example
<?php $fp=fopen("test.txt","w"); var_dump($fp); ?>
Output
This will produce following result −
resource(5) of type (stream)
Following example uses get_resource_type() function
Example
<?php $fp = fopen("test.txt", "w"); echo get_resource_type($fp) . "\n"; ?>
Output
This will produce following result −
stream