[Translation] [php extension development and embedded] Chapter 6th-return values

Source: Internet
Author: User
A user space function uses the return keyword to return information to its calling space, which is the same as the C syntax. return value

The user space function uses the return keyword to return information to its calling space, which is the same as the C language syntax.

For example:

function sample_long() {    return 42;  }  $bar = sample_long();

When sample_long () is called, 42 is returned and set to the $ bar variable. the equivalent code in C is as follows:

int sample_long(void) {    return 42;  }  void main(void) {    int bar = sample_long();  }

Of course, in C, you always know what the called function is and return based on the function prototype. Therefore, you need to define the variable stored in the returned result. in php user space processing, the variable type is dynamic, instead dependent on the zval type described in chapter 2nd "internal and external variables.

Return_value variable

You may think that your internal function should directly return a zval, or allocate a zval memory space and return zval * as follows *.

PHP_FUNCTION(sample_long_wrong)  {      zval *retval;        MAKE_STD_ZVAL(retval);      ZVAL_LONG(retval, 42);        return retval;  }

Unfortunately, this is incorrect. it does not force each function to implement zval allocation and return it. instead, the Zend Engine pre-allocates the space before calling the function. then, initialize the zval type to IS_NULL and pass the value as the parameter name return_value. the following are the correct practices:

PHP_FUNCTION(sample_long)  {      ZVAL_LONG(return_value, 42);      return;  }

Note that the PHP_FUNCTION () implementation does not directly return any value. Instead, the appropriate data is directly popped up to the return_value parameter, and the Zend Engine will post-process it after the internal function is executed.

Tip: ZVAL_LONG () macro is an encapsulation of multiple assignment operations:

Z_TYPE_P(return_value) = IS_LONG;  Z_LVAL_P(return_value) = 42;

Or more directly:

return_value->type = IS_LONG;  return_value->value.lval = 42;

The is_ref and refcount attributes of return_value should not be directly modified by internal functions. these values are initialized and processed by the Zend Engine when calling your function.

Now let's take a look at this special function and add it to the sample extension created in chapter 5th "your first extension. you only need to add this function under the sample_hello_world () function and add sample_long () to the php_sample_functions struct:

static function_entry php_sample_functions[] = {      PHP_FE(sample_hello_world, NULL)      PHP_FE(sample_long, NULL)      { NULL, NULL, NULL }  };

Now we can execute make to re-build the extension.

If everything is okay, you can run php and test the new function:

$ php -r 'var_dump(sample_long());

More compact macros

In terms of code readability and maintainability, the ZVAL _ * () macro contains the return_value variable. in this case, we can replace the ZVAL of the macro with RETVAL to omit the return_value during the call.

In the previous example, the implementation code of sample_long () can be reduced to the following:

PHP_FUNCTION(sample_long)  {      RETVAL_LONG(42);      return;  }

The following table lists the RETVAL macros in the Zend Engine. except for two special macros, the RETVAL macros are the same as the corresponding ZVAL macros except the return_value parameter.

Note that the TRUE and FALSE macros have no parentheses. this takes into account the Zend/PHP code standard deviation and retains the main one to maintain backward compatibility. if you fail to build the extension and receive the error message undefined macro RETVAL_TRUE (), make sure you have written the brackets when writing the two macros in the code.

Generally, when your function processes the returned value, it is ready to exit and return the control to the call scope. for this reason, another macro is designed for internal functions to RETURN: RETURN _ * () macro.

PHP_FUNCTION(sample_long)  {      RETURN_LONG(42);  }

Although not, this function will indeed return after the RETURN_LONG () macro is called. we can add php_printf () at the end of the function for testing:

PHP_FUNCTION(sample_long)  {      RETURN_LONG(42);      php_printf("I will never be reached.\n");  }

Php_printf (), as described in the content, because the call to RETURN_LONG () implicitly ends the function.

Like the RETVAL series, each simple type listed in the preceding table has a corresponding RETURN macro. like the RETVAL series, the RETURN_TRUE and RETURN_FALSE macros do not use parentheses.

More complex types, such as objects and arrays, are also returned through the return_value parameter. However, they cannot be created by a simple macro. even if the resource type has a RETVAL macro, it requires additional work to return the resource type. you will see how to return these types in chapter 8th to Chapter 11th.

Is it worth this trouble?

A unused Zend internal function is the return_value_used parameter. Consider the following user space code:

function sample_array_range() {      $ret = array();      for($i = 0; $i < 1000; $i++) {          $ret[] = $i;      }      return $ret;  }  sample_array_range();

Because the result is not stored in the variable when sample_array_range () is called, the array space of the 1000 elements created here will be completely wasted. of course, it is silly to call sample_array_range () in this way, but there is no good way to predict what will happen to you in the future?

Although the user space function cannot be accessed, the internal function can rely on the return_value_used parameter settings of all internal functions, and the meaningless behavior such as conditional jump.

PHP_FUNCTION (sample_array_range) {if (return_value_used) {int I;/* returns an array from 0 to 999 */array_init (return_value); for (I = 0; I <1000; I ++) {add_next_index_long (return_value, I) ;}return ;}else {/* error prompted */php_error_docref (NULL TSRMLS_CC, E_NOTICE, "Static return-only function called without processing output"); RETURN_NULL ();}}

To see the operation of this function, you only need to add this function to your sample. c source file and expose it to the php_sample_functions structure:

PHP_FE(sample_array_range, NULL)

For more information about how to handle the returned values of a function that is not used in a user space, see the zend_do_fcall_common_helper_SPEC function in Zend/zend_vm_execute.h. after processing the internal function call, checks whether the return value of the function is used. if not, the function is released.

Return reference value

You may already know from the php work in the user space, and the php function can return values in reference mode. due to implementation problems, you should avoid returning references in internal functions before php 5.1 because it cannot work. consider the following user space code snippet:

Function & sample_reference_a () {/* if the global space has no variable $ a, create it with the initial value NULL */if (! Isset ($ GLOBALS ['A']) {$ GLOBALS ['A'] = NULL;} return $ GLOBALS ['A'];} $ a = 'foo '; $ B = sample_reference_a (); $ B = 'bar ';

In this code snippet, it is like using $ B = & $ GLOBALS ['A]; or because of the global space, using $ B = & $; creates a reference for $ B as $.

Looking back at chapter 3rd "memory management", when the last row arrives, $ a and $ B actually contain the same value 'bar'. now let's look at the internal implementation of this function:

# If (PHP_MAJOR_VERSION> 5) | (PHP_MAJOR_VERSION = 5 & \ PHP_MINOR_VERSION> 0) PHP_FUNCTION (sample_reference_a) {zval ** a_ptr, *; /* find the variable $ a */if (zend_hash_find (& EG (symbol_table), "a", sizeof ("a"), (void **) from the global symbol table **) & a_ptr) = SUCCESS) {a = * a_ptr;} else {/* if $ GLOBALS ['A'] does not exist, create it */ALLOC_INIT_ZVAL (); zend_hash_add (& EG (symbol_table), "a", sizeof ("a"), & a, sizeof (zval *), NULL);}/* discard the old return value */Zval_ptr_dtor (return_value_ptr); if (! A-> is_ref & a-> refcount> 1) {/* $ a needs to be copied when writing. before use, you must first isolate */zval * newa; MAKE_STD_ZVAL (newa); * newa = * a; zval_copy_ctor (newa); newa-> is_ref = 0; newa-> refcount = 1; zend_hash_update (& EG (symbol_table ), "a", sizeof ("a"), & newa, sizeof (zval *), NULL); a = newa ;} /* set the new return value as the reference method and add refcount */a-> is_ref = 1; a-> refcount ++; * return_value_ptr = ;} # endif/* PHP> = 5.1.0 */

The return_value_ptr parameter is another common parameter passed by all internal functions. it is of the zval ** type and contains a pointer to return_value. by calling zval_ptr_dtor () on it, the zval * of the default return_value will be released. then you can freely select a new zval * to replace it. here, the variable $ a is selected. after zval is selectively isolated, set is_ref to 1, set to return_value_ptr.

If you compile and run this code now, you will get a segment error anyway. to make it work, you need to add the following code in php_sample.h:

#if (PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && \                            PHP_MINOR_VERSION > 0)  static      ZEND_BEGIN_ARG_INFO_EX(php_sample_retref_arginfo, 0, 1, 0)      ZEND_END_ARG_INFO ()  #endif /* PHP >= 5.1.0 */

In the php-5.4.9 used by the translator, the macro definition of ZEND_BEGIN_ARG_INFO_EX already contains the static modifier, so the corresponding needs to be modified in the example in this book, please note this during reading.

Next, use this structure when declaring your function in php_sample_functions:

#if (PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && \                            PHP_MINOR_VERSION > 0)      PHP_FE(sample_reference_a, php_sample_retref_arginfo)  #endif /* PHP >= 5.1.0 */

This structure will be learned in detail later in this chapter to provide important implication information for function calls to the Zend Engine. here it tells the Zend Engine that return_value needs to be overwritten and the correct address should be obtained from return_value_ptr. without this suggestion, the Zend Engine will simply set NULL in return_value_ptr, which may cause the program to crash when zval_ptr_dtor () is executed.

Each segment of this code is enclosed in the # if block, which indicates that the compiler only enables this support when the PHP version is later than or equal to 5.1. without these conditional commands, this extension cannot be compiled on php4 (because some elements contained in return_value_ptr do not exist ), php5.0 does not provide the correct function (a bug causes the returned reference to be copied as a value)

Reference return value

It is okay to use the return (syntax) structure to return values and variables to the caller. However, sometimes you need to return multiple values from a function. you can use arrays (we will "work with arrays and hash tables" in chapter 8th), or you can use parameter stack return values.

Reference value transfer during call

A simple way to pass variables by referencing is to require that you use the address get (&) before the parameter variable name during Calling. the following user space code:

function sample_byref_calltime($a) {      $a .= ' (modified by ref!)';  }  $foo = 'I am a string';  sample_byref_calltime(&$foo);  echo $foo;

The Get address (&) before the parameter variable name makes the actual zval sent to the function $ foo, rather than copying its content. this allows the function to modify this value by passing this parameter to return information. if sample_byref_calltime () is not used before $ foo when sample_byref_calltime () is called, modifications in the function will not affect the original variables.

To repeat this behavior at the C level, there is no need for special encoding. in your sample. c source code file sample_long (), create the following function:

PHP_FUNCTION (sample_byref_calltime) {zval * a; int addtl_len = sizeof ("(modified by ref !) ")-1; if (zend_parse_parameters (ZEND_NUM_ARGS () TSRMLS_CC," z ", & a) = FAILURE) {RETURN_NULL ();} if (! A-> is_ref) {/* Do not leave the function */return;}/* ensure that the variable is a string */convert_to_string (a) if it is not passed by reference ); /* expand the buffer of a to save the data to be appended */Z_STRVAL_P (a) = erealloc (Z_STRVAL_P (a), Z_STRLEN_P (a) + addtl_len + 1 ); memcpy (Z_STRVAL_P (a) + Z_STRLEN_P (a), "(modified by ref !) ", Addtl_len + 1); Z_STRLEN_P (a) + = addtl_len ;}

As usual, this function needs to be added to the php_sample_functions structure.

PHP_FE(sample_byref_calltime,        NULL)

The reference transfer value has been completely discarded in the translator's version (php-5.4.9 ZendEngine 2.4.0. earlier versions can be used in php. use the allow_call_time_pass_reference command in ini to enable it. pay attention to version issues during testing.

Reference during compilation

A more common method is to reference and pass the value during the compilation period. here, the function parameter is defined to be usable only in reference mode. Passing constants or other intermediate values (such as the result of function call) will cause errors, in this way, the function can store the result value for returning. the code for referencing and passing values during the compilation phase of a user space is as follows:

function sample_byref_compiletime(&$a) {      $a .= ' (modified by ref!)';  }  $foo = 'I am a string';  sample_byref_compiletime($foo);  echo $foo;

As you can see, the difference between this and the value passed by reference during the call is only that the location of the address operator is different. when you look at this function at the C level, the function code is exactly the same. the only difference is that the function declaration in the php_sample_functions block:

PHP_FE(sample_byref_compiletime, php_sample_byref_arginfo)

Php_sample_byref_arginfo is a constant structure. you need to define it before using it.

In fact, the is_ref check code can be deleted during the compilation phase, because it can always be referenced. However, it will not do any harm if it is left here.

In Zend Engine 1 (php4), this structure is a simple char * list. The first element specifies the length, followed by a tag set describing each function parameter.

static unsigned char php_sample_byref_arginfo[] =                                  { 1, BYREF_FORCE };

Here, 1 indicates that the vector contains only one parameter. the following elements describe the tag information specific to the parameter sequentially, and the second element describes the first parameter. if the second or third parameter is involved, the third and fourth elements must be added to the vector. the optional values of parameter information are as follows:

In Zend Engine 2 (php 5 +), you will use a more scalable structure that contains more information about the class, such as minimum and maximum parameter requirements, type hint, whether to force reference or not.

First, the parameter information structure is defined using one of the two macros. the simpler one is ZEND_BEGIN_ARG_INFO (), which requires two parameters:

ZEND_BEGIN_ARG_INFO(name, pass_rest_by_reference)

The name is very simple, that is, the name used when the structure is used elsewhere in the extension. In this example, the name is php_sample_byref_arginfo.

The meaning of pass_rest_by_reference is consistent with that of BYREF_FORCE_REST when the last element of the parameter information vector of Zend Engine 1 is used. if this parameter is set to 1, all parameters that are not explicitly described in the structure are considered to be parameters that reference passed values during compilation.

There is also an optional start Macro, which introduces two new options not available in Zend Engine 1, which is ZEND_BEGIN_ARG_INFO_EX ():

ZEND_BEGIN_ARG_INFO_EX(name, pass_rest_by_reference, return_reference,                               required_num_args)

Of course, name and pass_rest_by_reference share the same meaning as previously mentioned. As mentioned earlier in this chapter, return_reference tells Zend that your function needs to overwrite return_value_ptr with its own zval.

The last parameter, required_num_args, is another type of hint used to tell Zend to completely skip function calls when a call is considered incomplete.

After you have an appropriate start macro, it can be zero or multiple ZEND_ARG _ * INFO elements. the types and usage of these macros are shown in the following table.

Finally, all the parameter information structures set by macros using Zend Engine 2 must end with ZEND_END_ARG_INFO (). for your sample function, you need to select the following structure:

ZEND_BEGIN_ARG_INFO(php_sample_byref_arginfo, 0)      ZEND_ARG_PASS_INFO(1)  ZEND_END_ARG_INFO()

To make the extension compatible with Zend Engine 1 and 2, use the # ifdef statement to define the arg_info structure for both of them:

#ifdef ZEND_ENGINE_2  static      ZEND_BEGIN_ARG_INFO(php_sample_byref_arginfo, 0)          ZEND_ARG_PASS_INFO(1)      ZEND_END_ARG_INFO()  #else /* ZE 1 */  static unsigned char php_sample_byref_arginfo[] =                                  { 1, BYREF_FORCE };  #endif

Note that these code snippets are centralized. now it is time to create a real compilation phase to reference and pass the value. first, we put the php_sample_byref_arginfo block defined for Zend Engine 1 and 2 in the header file php_sample.h.

There are two options: Copy the PHP_FUNCTION (sample_byref_calltime) and rename it to PHP_FUNCTION (sample_byref_compiletime). Then, add a PHP_FE (limit, limit) line to php_sample_functions)

This method is easy to move and cannot be confused when it is modified after a while. this is just the sample code, so we can relax a little and use the PHP_FALIAS () you learned in the previous chapter to avoid code duplication.

In this way, the PHP_FUNCTION (sample_byref_calltime) is not assigned, but a line is directly added to php_sample_functions:

PHP_FALIAS(sample_byref_compiletime, sample_byref_calltime,      php_sample_byref_arginfo)

In chapter 5th, a user space function named sample_byref_compiletime () will be created. its internal implementation is the code of sample_byref_calltime (). php_sample_byref_arginfo is a special feature of this version.

Summary

This chapter describes how to return values from an internal function, including direct return values and reference methods, and return values through parameter stack reference. in addition, the parameter type implication structure zend_arg_info of Zend Engine 2 is also briefly understood.

In the next chapter, you will continue to explore the acceptance of basic zval parameters and the powerful type tricks using zend_parse_parameters.

The above is [Translation] [php extension development and embedded] Chapter 6th-return value content. For more information, see PHP Chinese website (www.php1.cn )!

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.