PHP - 退出或返回哪个更好?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3484050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - exit or return which is better?
提问by q0987
I would like to know in the following case which is a better option:
我想知道在以下情况下哪个是更好的选择:
In the PHP script, if the $fileSize
variable is larger than 100, I stop the script;
PHP脚本中,如果$fileSize
变量大于100,我就停止脚本;
Case I:
案例一:
<?php
if ( $fileSize > 100 )
{
$results['msg'] = 'fileSize is too big!';
echo json_encode( $results );
exit();
}
Case II:
案例二:
<?php
if ( $fileSize > 100 )
{
$results['msg'] = 'fileSize is too big!';
exit( json_encode( $results ) );
}
Case III:
案例三:
<?php
if ( $fileSize > 100 )
{
$results['msg'] = 'fileSize is too big!';
return( json_encode( $results ) );
}
Which of the three (3) options above is the best?
以上三 (3) 个选项中哪一个是最好的?
回答by Aziz
Since you are using exit
and return
within the global scope (not inside a function), then the behavior is almost the same.
由于您在全局范围内使用exit
和return
(不在函数内),因此行为几乎相同。
The difference in this case will appear if your file is called through include()
or require()
. exit
will terminate the program, while return
will take the control back to the calling script (where include
or require
was called).
如果您的文件是通过include()
或调用的,则在这种情况下会出现差异require()
。exit
将终止程序,同时return
将控制权带回到调用脚本(include
或被require
调用的地方)。
回答by Jeffrey Blake
I would tend to go with the return()
method, so that other scripts can continue executing. That way, if you ever use another script to call this one, it can do error-handling to deal with the case where the file is too large, as opposed to always halting execution.
我倾向于使用该return()
方法,以便其他脚本可以继续执行。这样,如果你曾经使用另一个脚本来调用这个脚本,它可以做错误处理来处理文件太大的情况,而不是总是停止执行。
回答by Crayon Violent
It depends...if your script is intended to do nothing else but output a message, and you don't want the script to do anything afterwards, exit() will work. Otherwise, use return.
这取决于...如果您的脚本除了输出消息之外什么都不做,并且您不希望脚本之后执行任何操作,exit() 将起作用。否则,使用返回。