PHP - 退出或返回哪个更好?
我想知道在以下情况下哪个是更好的选择:
在 PHP 脚本中,如果 $fileSize
变量大于 100,我会停止脚本;
案例一:
<?php
if ( $fileSize > 100 )
{
$results['msg'] = 'fileSize is too big!';
echo json_encode( $results );
exit();
}
案例二:
<?php
if ( $fileSize > 100 )
{
$results['msg'] = 'fileSize is too big!';
exit( json_encode( $results ) );
}
案例三:
<?php
if ( $fileSize > 100 )
{
$results['msg'] = 'fileSize is too big!';
return( json_encode( $results ) );
}
上述三 (3) 个选项中哪一个最好?
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;
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您在全局范围内(而不是在函数内)使用
exit
和return
,因此行为几乎相同。如果您的文件是通过
include()
或require()
调用的,则会出现这种情况的差异。exit
将终止程序,而return
会将控制权返回给调用脚本(其中include
或require
被称为)。Since you are using
exit
andreturn
within the global scope (not inside a function), then the behavior is almost the same.The difference in this case will appear if your file is called through
include()
orrequire()
.exit
will terminate the program, whilereturn
will take the control back to the calling script (whereinclude
orrequire
was called).我倾向于使用 return() 方法,以便其他脚本可以继续执行。这样,如果您使用另一个脚本来调用这个脚本,它可以执行错误处理来处理文件太大的情况,而不是总是停止执行。
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.这取决于...如果您的脚本除了输出一条消息之外什么都不做,并且您不希望脚本随后执行任何操作,则 exit() 将会起作用。否则,使用返回。
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 与 die() 一样终止程序。 手册
Exit terminates the program like die(). manual