Home Backend Development PHP Tutorial PHP: Detailed explanation of resource data type examples

PHP: Detailed explanation of resource data type examples

May 16, 2018 pm 04:08 PM

What is a resource data type?

The resource data type is introduced in PHP4. Resource is a special variable type that holds a reference to an external resource: such as an open file, database connection, graphics canvas area, etc.

Resources are created and used through specialized functions.

Use of resource variables in PHP

$fp = fopen("test.txt", "rw");  
  
var_dump($fp);  
  
fclose($fp);
Copy after login

Print results: resource(5) of type (stream)

Number 5: Indicates that the resource ID is 5, the specific meaning follows introduce.

stream: resource type name.

Resource ID

The kernel stores the registered resource variables in a HashTable, and uses the key in the HashTable where the resource is located as the resource ID.

So, in fact, the resource variable in PHP actually stores an integer, and the corresponding resource in the HashTable is found through this ID.

#define Z_RESVAL(zval)          (zval).value.lval  
#define Z_RESVAL_P(zval)        Z_RESVAL(*zval)  
#define Z_RESVAL_PP(zval)       Z_RESVAL(**zval)
Copy after login

The above macro is the API used by ZE in the kernel to assign values ​​to resource variables. It can be seen that it is indeed an assignment to an integer variable.

Resource type name

In order to distinguish resource types, we need to define type names for the resources we define.

#define MY_RES_NAME "my_resource" //资源类型名称,PHP通过var_dump打印资源变量时会看到这个名称  
static int my_resource_descriptor;  
  
ZEND_MINIT_FUNCTION(jinyong)  
{  
    my_resource_descriptor = zend_register_list_destructors_ex(NULL, NULL, MY_RES_NAME, module_number);//向内核中注册新的资源类型  
}
Copy after login

ZEND_MINIT_FUNCTION(jinyong) will execute ZEND_MINIT_FUNCTION of all extensions when PHP is loaded into memory as a SAPI (for example, Apache's mod_php5 extension).

Among them, jinyong is the name of the current extension. For example, the name of the extension at this time is jinyong

For the convenience of understanding, we think of it as the extension registering a new resource type with the kernel during initialization.

Creating resource variables

The resource type has been successfully registered, and a differentiated type name has been defined for the resource. Variables for this resource can now be used.

Implementing the fopen function in PHP:

PHP_FUNCTION(my_fopen)  
{  
    zval *res;  
  
    char *filename, *mode;  
      
    int filename_strlen, mode_strlen;  
  
    FILE *fp;  
      
    if(zend_parse_parameters(ZEND_NUM_ARGS TSRMLS_CC, "s|s",  &filename, &filename_strlen, &mode, &mode_strlen) == FAILURE){  
        RETURN_FALSE;  
    }  
  
    //此处省略了对参数的有效性验证  
    fp = fopen(filename, mode);  
  
    ZEND_REGISTER_RESOURCE(res, fp, my_resource_descriptor);//向全局变量&EG(regular_list)中注册资源变量,并将对应HashTable的ID赋值给res  
  
    RETURN_RESOURCE(res);//向PHP返回资源变量  
}
Copy after login

Here, the function named my_fopen in PHP is defined. my_fopen(string $file_name, string $mode)

Implements the fclose function in PHP:

PHP_FUNCTION(my_fclose)  
{  
    zval *res;  
      
    FILE *fp;  
  
    if(zend_parse_parameters(ZEND_NUM_ARGS TSRMS_CC, "r", &res) == FAILURE){  
        RETURN_FALSE;  
    }  
  
    if(Z_TYPE_P(res) == IS_RESOURCE){//判断变量类型是否是资源类型  
        zend_hash_index_del(&EG(regular_list), Z_RESVAL_P(res));//EG就类似于PHP中的$_GLOBALS。在全局资源变量regular_list中删除对应ID的资源  
    }else{  
        php_error_docref(NULL TSRMLS_CC, E_WARNING, "参数必须是资源类型变量");  
        RETURN_FALSE;  
    }  
  
    RETURN_TRUE;  
}
Copy after login

defines the function named my_fclose in PHP. my_fclose($resource)

Using the method in the custom extension in PHP

my_fwrite($fp, "aaTest");  
  
var_dump($fp);  
  
my_fclose($fp);  
  
var_dump($fp);
Copy after login

can open and close resources normally.

Release resources

Since the PHP4 Zend engine has introduced a resource counting system, it can automatically detect that a resource is no longer referenced (same as Java). In this case, all external resources used by this resource will be released by the garbage collection system. Therefore, it is rarely necessary to manually free memory using some free-result function.

Note: Persistent database connections are special, they will not be destroyed by the garbage collection system.

In the next section, we will explain the "null value (null)" among the two special data types.

The above is the detailed content of PHP: Detailed explanation of resource data type examples. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What data type should be used for gender field in MySQL database? What data type should be used for gender field in MySQL database? Mar 14, 2024 pm 01:21 PM

In a MySQL database, gender fields can usually be stored using the ENUM type. ENUM is an enumeration type that allows us to select one as the value of a field from a set of predefined values. ENUM is a good choice when representing a fixed and limited option like gender. Let's look at a specific code example: Suppose we have a table called "users" that contains user information, including gender. Now we want to create a field for gender, we can design the table structure like this: CRE

How to find resources on 115 network disk How to find resources on 115 network disk Feb 23, 2024 pm 05:10 PM

There will be a lot of resources in the 115 network disk, so how to find resources? Users can search for the resources they need in the software, then enter the download interface, and then choose to save to the network disk. This introduction to the method of finding resources on 115 network disk can tell you the specific content. The following is a detailed introduction, come and take a look. How to find resources on 115 network disk? Answer: Search the content in the software, and then click to save to the network disk. Detailed introduction: 1. First enter the resources you want in the app. 2. Then click the keyword link that appears. 3. Then enter the download interface. 4. Click Save to network disk inside.

What is the best data type for gender fields in MySQL? What is the best data type for gender fields in MySQL? Mar 15, 2024 am 10:24 AM

In MySQL, the most suitable data type for gender fields is the ENUM enumeration type. The ENUM enumeration type is a data type that allows the definition of a set of possible values. The gender field is suitable for using the ENUM type because gender usually only has two values, namely male and female. Next, I will use specific code examples to show how to create a gender field in MySQL and use the ENUM enumeration type to store gender information. The following are the steps: First, create a table named users in MySQL, including

Why did Han Xiaoquan suddenly have no resources? Why did Han Xiaoquan suddenly have no resources? Feb 24, 2024 pm 03:22 PM

Han Xiaoquan is a software that can watch many Korean dramas, so why is there suddenly no resource? This software may have no resources due to network problems, version problems, or copyright issues. This article about the reason why Han Xiaoquan suddenly has no resources can tell you the specific content. The following is a detailed introduction, come and take a look. Why did Han Xiaoquan suddenly have no resources? Answer: Due to network problems, version problems, and copyright issues, detailed introduction: 1. Solution to network problems: You can choose a different network, and then log in to the software again to try. 2. Solution to version problems: Users can download the latest version of this software from the official website. 3. Solutions to copyright issues: Some Korean dramas are removed from the shelves due to copyright issues. You can choose other Korean dramas to watch.

Mind map of Python syntax: in-depth understanding of code structure Mind map of Python syntax: in-depth understanding of code structure Feb 21, 2024 am 09:00 AM

Python is widely used in a wide range of fields with its simple and easy-to-read syntax. It is crucial to master the basic structure of Python syntax, both to improve programming efficiency and to gain a deep understanding of how the code works. To this end, this article provides a comprehensive mind map detailing various aspects of Python syntax. Variables and Data Types Variables are containers used to store data in Python. The mind map shows common Python data types, including integers, floating point numbers, strings, Boolean values, and lists. Each data type has its own characteristics and operation methods. Operators Operators are used to perform various operations on data types. The mind map covers the different operator types in Python, such as arithmetic operators, ratio

How to refresh Dying Light resources infinitely How to refresh Dying Light resources infinitely Jan 24, 2024 pm 04:03 PM

In the game Dying Light, many players may be surrounded by countless zombies in the early stage due to lack of resources. Sometimes they will also take risks to rescue trapped wanderers, and these wanderers may also provide some side tasks, which will be richly rewarded upon completion. Dying Light Unlimited Resource Acquisition First, find a relief package and put it in the warehouse. On the home page of the [Inventory], select an item with a larger quantity and click with the left mouse button when selected. 2. Then, press [ESC] without moving the mouse. Press F+A quickly. Just press once. After about 0.25 seconds, when you feel that the warehouse page is about to pop up, press the left and right buttons of the mouse. Do not move the mouse and do not press and hold. The prompt to store the items will pop up and it will be successful. 3Finally, find [Disaster Package] in the warehouse and be prompted by

What is the best data type choice for gender field in MySQL? What is the best data type choice for gender field in MySQL? Mar 14, 2024 pm 01:24 PM

When designing database tables, choosing the appropriate data type is very important for performance optimization and data storage efficiency. In the MySQL database, there is really no so-called best choice for the data type to store the gender field, because the gender field generally only has two values: male or female. But for efficiency and space saving, we can choose a suitable data type to store the gender field. In MySQL, the most commonly used data type to store gender fields is the enumeration type. An enumeration type is a data type that can limit the value of a field to a limited set.

Detailed explanation of how to use Boolean type in MySQL Detailed explanation of how to use Boolean type in MySQL Mar 15, 2024 am 11:45 AM

Detailed explanation of how to use Boolean types in MySQL MySQL is a commonly used relational database management system. In practical applications, it is often necessary to use Boolean types to represent logical true and false values. There are two representation methods of Boolean type in MySQL: TINYINT(1) and BOOL. This article will introduce in detail the use of Boolean types in MySQL, including the definition, assignment, query and modification of Boolean types, and explain it with specific code examples. 1. The Boolean type is defined in MySQL and can be

See all articles