在幕后,PHP检查函数中的return
语句void
,如果它们指定了返回值,则会引发编译时错误:
/* `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;
}
否则,void
函数的编译会像往常一样工作。return
没有值隐式返回NULL
:
if (!expr_ast) {
expr_node.op_type = IS_CONST;
ZVAL_NULL(&expr_node.u.constant);
并且每个函数都在末尾隐式编译return
:
zend_emit_final_return(0);
其返回值为NULL
:
zn.op_type = IS_CONST;
if (return_one) {
ZVAL_LONG(&zn.u.constant, 1);
} else {
ZVAL_NULL(&zn.u.constant);
}