简体   繁体   English

PHP 7.1中的隐式void返回?

[英]Implicit void return in PHP 7.1?

I found in here the new spec: https://wiki.php.net/rfc/void_return_type 我在这里找到了新的规范: https//wiki.php.net/rfc/void_return_type

function lacks_return(): void {
    // valid
}
function returns_nothing(): void {
    return; // valid
}
function returns_void(): void {
    return void; // valid
}

Ask: Do you know what happens behind the scene. 问:你知道幕后发生了什么。 Will the lacks_return function return actually void ? lacks_return函数返回实际上是否void

Behind the scenes, PHP checks for return statements in void functions and, if they specify a return value, throws a compile-time error: 在幕后,PHP 检查void函数中的return语句 ,如果它们指定了返回值,则抛出编译时错误:

/* `return ...;` is illegal in a void function (but `return;` isn't) */
if (return_info->type_hint == IS_VOID) {
    if (expr) {
        if (expr->op_type == IS_CONST && Z_TYPE(expr->u.constant) == IS_NULL) {
            zend_error_noreturn(E_COMPILE_ERROR,
                "A void function must not return a value "
                "(did you mean \"return;\" instead of \"return null;\"?)");
        } else {
            zend_error_noreturn(E_COMPILE_ERROR, "A void function must not return a value");
        }
    }
    /* we don't need run-time check */
    return;
}

Otherwise, compilation of void functions works like normal. 否则, void函数的编译就像普通函数一样。 return without a value implicitly returns NULL : 没有值的return隐式返回NULL

if (!expr_ast) {
    expr_node.op_type = IS_CONST;
    ZVAL_NULL(&expr_node.u.constant);

And every function is compiled with an implicit return at the end : 并且每个函数都在最后使用隐式return进行编译

zend_emit_final_return(0);

Whose return value is NULL : 其返回值为NULL

zn.op_type = IS_CONST;
if (return_one) {
    ZVAL_LONG(&zn.u.constant, 1);
} else {
    ZVAL_NULL(&zn.u.constant);
}

You could have tested this yourself pretty easily: 你可以很容易地自己测试一下:

function lacks_return(): void {
}

function returns_nothing(): void {
    return;
}

echo gettype(lacks_return()); // NULL
echo gettype(returns_nothing()); // NULL

So the answer is yes - there is an implicit empty (null) return so you could either use an empty return or skip it completely. 所以答案是肯定的 - 有一个隐式的空(null)返回,所以你可以使用空返回或完全跳过它。 Which kind of makes sense - returning nothing is the same as not returning anything? 哪种有意义 - 什么都不返回就像没有返回什么一样?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM