PHP 7.1中的隐式返回值?
我在这里新规范发现:https://wiki.php.net/rfc/void_return_typePHP 7.1中的隐式返回值?
function lacks_return(): void {
// valid
}
function returns_nothing(): void {
return; // valid
}
function returns_void(): void {
return void; // valid
}
问:你知不知道幕后发生了什么。 lacks_return
函数实际上会返回void
吗?
你可以自己已经很容易地测试这样的:
function lacks_return(): void {
}
function returns_nothing(): void {
return;
}
echo gettype(lacks_return()); // NULL
echo gettype(returns_nothing()); // NULL
因此,答案是肯定的 - 有一个隐含的空(NULL)回报,所以你既可以使用一个空的回报或者完全跳过它。哪一种是有道理的 - 什么都不返回就像没有返回任何东西一样?
''var_dump'会比'echo'更好这个例子 –
please also consid呃新的无效类型http://*.com/questions/29792827/void-as-return-type。这看起来像主要课程。我真的在寻找一些调试,来自符号表或PHP AST解释。但这也是很棒的bacuska。 – prosti
@RobbieAverill gettype()返回一个字符串,为什么var_dump()是一个字符串? :) –
在幕后,PHP checks for return
statements in void
functions,如果他们指定一个返回值,抛出一个编译时错误:
/* `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
without a value implicitly returns NULL
:
if (!expr_ast) {
expr_node.op_type = IS_CONST;
ZVAL_NULL(&expr_node.u.constant);
而且每个功能is compiled with an implicit return
at the end:
zend_emit_final_return(0);
zn.op_type = IS_CONST;
if (return_one) {
ZVAL_LONG(&zn.u.constant, 1);
} else {
ZVAL_NULL(&zn.u.constant);
}
'这个函数返回也隐含空' - 是 –
NULL http://ideone.com?/AXErws或https://3v4l.org/RJRoR – 2016-11-14 01:04:10