Home Backend Development PHP Tutorial PHP return value return statement usage detailed explanation

PHP return value return statement usage detailed explanation

Jun 27, 2017 am 09:32 AM
php return usage Detailed explanation statement return

In Programming language, a function or a method generally returns a value, but there are also situations where it does not return a value. At this time, these functions only process some transactions and do not return, or in other words There is no explicit return value, it has a proprietary keyword procedure in Pascal language. In PHP, functions have return values, which can be divided into two situations: using a return statement to explicitly return and returning NULL without a return statement.

return statement

When using the return statement, PHP returns a variable of the specified type to the user-defined function. The same way we view the source code, after performing lexical analysis and syntax analysis on the return keyword, we generate intermediate code. From the Zend/zend_language_parser.y file, it can be confirmed that the intermediate code generated calls the zend_do_return function.

void zend_do_return(znode *expr, int do_end_vparse TSRMLS_DC) /* {{{ */{
 zend_op *opline;
   int start_op_number, end_op_number;     if (do_end_vparse) {
       if (CG(active_op_array)->return_reference                && !zend_is_function_or_method_call(expr)) {
           zend_do_end_variable_parse(expr, BP_VAR_W, 0 TSRMLS_CC);/* 处理返回引用 */
       } else {
           zend_do_end_variable_parse(expr, BP_VAR_R, 0 TSRMLS_CC);/* 处理常规变量返回 */
       }
   } 
  ...// 省略  取其它中间代码操作 
   opline->opcode = ZEND_RETURN;     if (expr) {
       opline->op1 = *expr;         if (do_end_vparse && zend_is_function_or_method_call(expr)) {
           opline->extended_value = ZEND_RETURNS_FUNCTION;
       }
   } else {
       opline->op1.op_type = IS_CONST;
       INIT_ZVAL(opline->op1.u.constant);
   } 
   SET_UNUSED(opline->op2);}/* }}} */
Copy after login

The generated intermediate code is ZEND_RETURN. When the return value is a usable expression, the type of the first operand is the operation type of the expression, otherwise the type is IS_CONST. This is useful when subsequent calculations execute intermediate code functions. Depending on the operands, the ZEND_RETURN intermediate code will execute ZEND_RETURN_SPEC_CONST_HANDLER, ZEND_RETURN_SPEC_TMP_HANDLER or ZEND_RETURN_SPEC_TMP_HANDLER. The execution flows of these three functions are basically similar, including the handling of some errors. Here we take ZEND_RETURN_SPEC_CONST_HANDLER as an example to illustrate the execution process of the function return value:

static int ZEND_FASTCALL  ZEND_RETURN_SPEC_CONST_HANDLER(ZEND_OPCODE_HANDLER_ARGS){
 zend_op *opline = EX(opline);
   zval *retval_ptr;
   zval **retval_ptr_ptr; 
     if (EG(active_op_array)->return_reference == ZEND_RETURN_REF) {         //  返回引用时不允许常量和临时变量
       if (IS_CONST == IS_CONST || IS_CONST == IS_TMP_VAR) {   
           /* Not supposed to happen, but we'll allow it */
           zend_error(E_NOTICE, "Only variable references \                should be returned by reference");
           goto return_by_value;
       } 
       retval_ptr_ptr = NULL;  //  返回值         if (IS_CONST == IS_VAR && !retval_ptr_ptr) {
           zend_error_noreturn(E_ERROR, "Cannot return string offsets by reference");
       }         if (IS_CONST == IS_VAR && !Z_ISREF_PP(retval_ptr_ptr)) {
           if (opline->extended_value == ZEND_RETURNS_FUNCTION &&
               EX_T(opline->op1.u.var).var.fcall_returned_reference) {
           } else if (EX_T(opline->op1.u.var).var.ptr_ptr ==
                   &EX_T(opline->op1.u.var).var.ptr) {
               if (IS_CONST == IS_VAR && !0) {
                     /* undo the effect of get_zval_ptr_ptr() */
                   PZVAL_LOCK(*retval_ptr_ptr);
               }
               zend_error(E_NOTICE, "Only variable references \                 should be returned by reference");
               goto return_by_value;
           }
       }         if (EG(return_value_ptr_ptr)) { //  返回引用
           SEPARATE_ZVAL_TO_MAKE_IS_REF(retval_ptr_ptr);   //  is_refgc设置为1
           Z_ADDREF_PP(retval_ptr_ptr);    //  refcountgc计数加1             (*EG(return_value_ptr_ptr)) = (*retval_ptr_ptr);
       }
   } else {return_by_value: 
       retval_ptr = &opline->op1.u.constant;         if (!EG(return_value_ptr_ptr)) {
           if (IS_CONST == IS_TMP_VAR) {             }
       } else if (!0) { /* Not a temp var */
           if (IS_CONST == IS_CONST ||
               EG(active_op_array)->return_reference == ZEND_RETURN_REF ||
               (PZVAL_IS_REF(retval_ptr) && Z_REFCOUNT_P(retval_ptr) > 0)) {
               zval *ret; 
               ALLOC_ZVAL(ret);
               INIT_PZVAL_COPY(ret, retval_ptr);   //  复制一份给返回值 
               zval_copy_ctor(ret);
               *EG(return_value_ptr_ptr) = ret;
           } else {
               *EG(return_value_ptr_ptr) = retval_ptr; //  直接赋值
               Z_ADDREF_P(retval_ptr);
           }
       } else {
           zval *ret; 
           ALLOC_ZVAL(ret);
           INIT_PZVAL_COPY(ret, retval_ptr);    //  复制一份给返回值 
           *EG(return_value_ptr_ptr) = ret;    
       }
   }     return zend_leave_helper_SPEC(ZEND_OPCODE_HANDLER_ARGS_PASSTHRU);   //  返回前执行收尾工作}
Copy after login

The return value of the function is stored in *EG(return_value_ptr_ptr) when the program is executed. The ZE kernel distinguishes between value return and reference return, and on this basis, constants, temporary variables and other types of variables are treated differently when returned. Before the return is executed, the ZE kernel clears the variables used inside the function by calling the zend_leave_helper_SPEC function. This is one of the reasons why the ZE kernel automatically adds NULL returns to functions.

Function without return statement

In PHP, there is no concept of procedure, only functions without return value. But for functions that have no return value, the PHP kernel will "help you" add a NULL as the return value. This "helping you" operation is also performed when generating intermediate code. The function zend_do_end_function_declaration needs to be executed when parsing each function. There is a statement in this function:

zend_do_return(NULL, 0 TSRMLS_CC);
Copy after login

Combined with the previous content, we know that the function of this statement is to return NULL. This is why functions without a return statement return NULL.

The return value of the internal function is passed through a variable named return_value. This variable is also a parameter in the function, which can be seen after the PHP_FUNCTION function is expanded. This parameter always contains a zval container with pre-allocated space, so you can directly access its members and modify them without first executing the MAKE_STD_ZVAL macro on the return_value. In order to make it easier to return results from functions and save the trouble of directly accessing the internal structure of the zval container, ZEND provides a large set of macro commands to complete these related operations. These macros automatically set the type and value.

Macros that return values ​​directly from functions:

RETURN_RESOURCE(resource) returns a resource.

RETURN_BOOL(bool) Returns a Boolean value.

RETURN_NULL() returns a null value.

RETURN_LONG(long) Returns a long integer.

RETURN_DOUBLE(double) Returns a double-precision floating point number.

RETURN_STRING(string, duplicate) Returns a string. duplicate indicates whether this character is copied using estrdup().

RETURN_STRINGL(string, length, duplicate) returns a fixed-length string. The rest is the same as RETURN_STRING. This macro is faster and binary safe.

RETURN_EMPTY_STRING() returns an empty string.

RETURN_FALSE Returns a Boolean value false.

RETURN_TRUE Returns a boolean true value.

Macro for setting function return value:

RETVAL_RESOURCE(resource) Set the return value to a specified resource.

RETVAL_BOOL(bool) Set the return value to a specified Boolean value.

RETVAL_NULL Set the return value to a null value

RETVAL_LONG(long) Set the return value to a specified long integer.

RETVAL_DOUBLE(double) Set the return value to a specified double-precision floating point number.

RETVAL_STRING(string, duplicate) Set the return value to a specified string. The meaning of duplicate is the same as RETURN_STRING.

RETVAL_STRINGL(string, length, duplicate) Set the return value to a specified fixed-length string. The rest is the same as RETVAL_STRING. This macro is faster and binary safe.

RETVAL_EMPTY_STRING Set the return value to an empty string.

RETVAL_FALSE Set the return value to Boolean false.

RETVAL_TRUE Set the return value to Boolean true.

If you need to return complex types of data such as arrays and objects, you need to call array_init() and object_init() first, or you can use the corresponding hash function to directly operate return_value. Since these types are mainly composed of miscellaneous things, there are no corresponding macros for them.



The above is the detailed content of PHP return value return statement usage detailed explanation. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles