What is a Resource type in PHP? What is it for?
I’m new to the PHP language, studying it, I came across a special type available through the language, type resource . I found a definition for it:
Resource
A resource is a special variable, which maintains a reference to a
external resource. Features are created and used by special functions.
What is a resource type? What is it for? What is its applicability in practice?
resource is of the php types, it is using for various purposes how to make connections with database, open / manipulate files or even work with streams.
As the manual basically talks about resorce is something returned through a specific function (it can be fopen , mysqli_connect etc) that if communicated with something external in other words it is a handler.
Well, for me the word resource has a very clear meaning and it is a bit difficult to explain the meaning of a word that is self-explanatory.
Maybe with an analogy, let it be clear what it is: If you think that a certain thing can provide means or directives to get / reach another thing, then just think that these means are nothing more than resources.
So in PHP it really makes sense for a connection link to be a resource, a stream / channel from an FTP connection, a file handler created by fopen (), or a connection socket. All of them are “points” from which other actions are taken to arrive at something / result.
Resource types were created in PHP 3 to compensate for the lack of objects, so of course you could (actually you might) think they are analogous to objects where functions returning resources would be object constructors and manipulating functions through the resource would be like methods of these objects.
Resource –
According to the official PHP documentation, it is “A resource is a special variable that maintains a reference to an external resource. Resources are created and used by special functions.”
Curl – makes requests for sending and downloading data (Usually used to communicate with Webservices (SOAP / REST) p>
XML to work with XML in PHP natively;
Imap for email (sending / receiving), manipulation of electronic mailboxes.
ODBC / mysql / dbase / dba for manipulating databases, among others.
What is resource type in php
Resource — это специальная переменная, содержащая ссылку на внешний ресурс. Ресурсы создаются и используются специальными функциями. Полный перечень этих функций и соответствующих типов ресурсов ( resource ) смотрите в приложении.
Смотрите также описание функции get_resource_type() .
Преобразование в ресурс
Поскольку тип resource содержит специальные указатели на открытые файлы, соединения с базой данных, области изображения и тому подобное, преобразование в этот тип не имеет смысла.
Освобождение ресурсов
Благодаря системе подсчёта ссылок, введённой в Zend Engine, определение отсутствия ссылок на ресурс происходит автоматически, после чего он освобождается сборщиком мусора. Поэтому очень редко требуется освобождать память вручную.
Замечание: Постоянные соединения с базами данных являются исключением из этого правила. Они не уничтожаются сборщиком мусора. Подробнее смотрите в разделе о постоянных соединениях.
User Contributed Notes 1 note
‘stream’ is a general resource type and can have specific subtypes (imap, pop, curl . ). Casting from ‘stream’ to them makes sense alright.
E.g. Making OAUTH2 work for imap, but still use the normal imap_ functions. Just open a ssl:// stream to the IMAP server with stream_socket_client(), send the «AUTHENTICATE XOAUTH2 . » authentication with valid token and then use the imap_ functions on the casted ‘stream’ to ‘imap’ resource.
Not being able to cast from ‘stream’ to ‘imap’ makes it necessary to use 3rd party solutions, like php-imap. Doesn’t have to be necessary, if the cast would be possible.
PHP Resources
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
Output
This will produce following result −
Following example uses get_resource_type() function
Example
Output
This will produce following result −
What is a Resource type in PHP? What is it for?
I’m new to the PHP language, studying it, I came across a special type available through the language, type resource . I found a definition for it:
Resource
A resource is a special variable, which maintains a reference to a
external resource. Features are created and used by special functions.
What is a resource type? What is it for? What is its applicability in practice?
resource is of the php types, it is using for various purposes how to make connections with database, open / manipulate files or even work with streams.
As the manual basically talks about resorce is something returned through a specific function (it can be fopen , mysqli_connect etc) that if communicated with something external in other words it is a handler.
Well, for me the word resource has a very clear meaning and it is a bit difficult to explain the meaning of a word that is self-explanatory.
Maybe with an analogy, let it be clear what it is: If you think that a certain thing can provide means or directives to get / reach another thing, then just think that these means are nothing more than resources.
So in PHP it really makes sense for a connection link to be a resource, a stream / channel from an FTP connection, a file handler created by fopen (), or a connection socket. All of them are “points” from which other actions are taken to arrive at something / result.
Resource types were created in PHP 3 to compensate for the lack of objects, so of course you could (actually you might) think they are analogous to objects where functions returning resources would be object constructors and manipulating functions through the resource would be like methods of these objects.
Resource –
According to the official PHP documentation, it is “A resource is a special variable that maintains a reference to an external resource. Resources are created and used by special functions.”
Curl – makes requests for sending and downloading data (Usually used to communicate with Webservices (SOAP / REST) p>
XML to work with XML in PHP natively;
Imap for email (sending / receiving), manipulation of electronic mailboxes.
ODBC / mysql / dbase / dba for manipulating databases, among others.