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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:56:29  来源:igfitidea点击:

PHP - exit or return which is better?

phpterminate

提问by q0987

I would like to know in the following case which is a better option:

我想知道在以下情况下哪个是更好的选择:

In the PHP script, if the $fileSizevariable 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 exitand returnwithin the global scope (not inside a function), then the behavior is almost the same.

由于您在全局范围内使用exitreturn(不在函数内),因此行为几乎相同。

The difference in this case will appear if your file is called through include()or require(). exitwill terminate the program, while returnwill take the control back to the calling script (where includeor requirewas 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() 将起作用。否则,使用返回。

回答by Iznogood

Exit terminates the program like die(). manual

Exit 像 die() 一样终止程序。手动的