PHP Resource Type instance sharing

Source: Internet
Author: User
In PHP, we often use a resource type variable. For example: MySQL connection, file handle, and so on. These variables cannot be represented by scalar, so how do you connect the resource variables in PHP to the resources in the C language in the Zend kernel?

One, the use of resource variables in PHP

    1. $fp = fopen ("Test.txt", "RW");    Var_dump ($FP);    Fclose ($FP);


Printed Result: Resource (5) of type (stream)

The number 5: Indicates a resource ID of 5, which is described later.

Stream: Resource type name.

Second, the resource ID

The kernel stores the registered resource variables in a hashtable and takes the key in the hashtable of the resource as the resource ID.

So, in fact, the resource variables in PHP actually store an integer type, which is the ID to find the corresponding resource in Hashtable.

    1. #define Z_RESVAL (Zval)          (zval). Value.lval  #define Z_RESVAL_P (zval)        z_resval (*zval)  #define Z_ RESVAL_PP (Zval)       z_resval (**zval)

The above macro, which is the API for assigning a value to a resource variable in the kernel, shows that the ze is indeed assigned to an integer variable.

Iii. Resource type name

To differentiate between resource types, you need to define the type name for the resource that we define.

#define MY_RES_NAME "My_resource"//resource type name, PHP will see this name when you print the resource variable 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);//Register a new resource type in the kernel  }


Zend_minit_function (Jinyong) will perform all the extended zend_minit_function when PHP is loaded into memory as a SAPI (for example, an Apache MOD_PHP5 extension).

Where Jinyong, is the name of the current extension. For example, the name of the extension is Jinyong

Here, for the sake of understanding, we think of it as an extension that, when initialized, registers a new resource type with the kernel.

Iv. Creating resource variables

The resource type has been registered successfully, and the distinguished type name is defined for the resource. You can now use the variables for this resource.

Implement the Fopen function in PHP:

    1. 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;      }        Validation of the parameters is omitted here      fp = fopen (filename, mode);        Zend_register_resource (res, FP, my_resource_descriptor);//Register resource variables in global variable &eg (regular_list), and assigns the ID of the corresponding hashtable to res        Return_resource (res);//returns the resource variable to PHP  }

Here, a function named My_fopen is defined in PHP. My_fopen (String $file _name, String $mode)

Implement the Fclose function in PHP:

    1. 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) {//Determine if the variable type is a resource type          Zend_hash_index_del (&eg (regular_list), z_resval_p (res)) //eg is similar to the $_globals in PHP. Delete the resource of the corresponding ID in the global resource variable regular_list      }else{          php_error_docref (NULL tsrmls_cc, e_warning, "parameter must be a resource type variable");          Return_false;      }        return_true;  }

Defines a function in PHP with the name My_fclose. My_fclose ($resource)

V. Compile, install extensions, restart PHP-FPM or MOD_PHP5, etc.

Vi. methods used in custom extensions in PHP

    1. My_fwrite ($fp, "aatest");    Var_dump ($FP);    My_fclose ($FP);    Var_dump ($FP);

You can open and close the resource normally.

Seven, we often use the database connection resources in PHP, file handle resources, but they usually do not need us to manually release, there is no memory leak problem, how is this implemented?

    1. My_resource_descriptor = ZEND_REGISTER_LIST_DESTRUCTORS_EX (null, NULL, My_res_name, module_number);//Register a new resource type in the kernel

Back to the beginning of the registered resource type, see the first parameter of ZEND_REGISTER_LIST_DESTRUCTORS_EX, which is a pointer to the destructor.

Then, if you need to implement automatic deallocation, you only need to define destructors and pass function pointers.

Look at one more question:

    1. $fp = fopen ("Test.txt", "RW");    Var_dump ($FP);    Fclose ($FP); This does not use Fclose to release resources    unset ($FP);//Use unset  to release//unset no problem, $FP variables are released normally. However, $fp corresponds to a real open file resource handle resource will never be released until MOD_PHP5 or PHP-FPM restarts  //Can be seen, the need to define a destructor when registering a resource type


To define a destructor:

static void Php_myres_dtor (Zend_rsrc_list_entry *rsrc tsrmls_dc) {//The destructor is called when a parameter of the current resource variable is accepted      FILE *FP = (file*) rsrc->ptr;      Fclose (FP);  }    Zend_minit_function (Jinyong)  {      my_resource_descriptor = ZEND_REGISTER_LIST_DESTRUCTORS_EX (php_myres_ Dtor, NULL, My_res_name, Module_number);  }
    • In PHP, the so-called resource variables, in fact, by storing integer values, in the kernel global resource variable list eg (regular_list) to find the corresponding pointer, and the corresponding operation.

A resource type is a special variable that holds a reference to an external resource. Resources are created and used through specialized functions.

such as database connection, open file, graphics canvas area, etc.

The resource type is actually just an integer, and the kernel can look for the data that is needed in a similar resource pool based on this integer value.

Example 1, an example of a file operation:

code example:

<?php$file=fopen (' A.txt ', ' r ');//Use the fopen function to open a file get handle.  fread ($file, 1024);//After the handle is passed to the Fread function, the file can be subsequently manipulated.

Example 2, examples of database operations:

code example:

<?php$result=mysql_query (' select * from Tbale '); the//mysql_query function executes a SQL, if it fails, returns false, succeeds, the query results are cached, and the resource ID is returned ( Similar to: Resource id#42) is a handle to the resource.  Mysql_num_row ($result);//Use this handle to manipulate the resources in the cache to return the number of  mysql_fetch_row ($result) that are queried, or use the handle to manipulate the resources in the cache. To return the query structure

Description
A list of functions that use and destroy resources.
You can use the Is_resource () function to determine whether a variable is a resource, and the function Get_resource_type () returns the type of the resource.

PHP resource variables, the reason is not to worry about similar MySQL connection not release problems, but also because the extension of the definition of the destructor method, help to automatically release.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.