PHP - 退出或返回哪个更好?

发布于 2024-09-14 19:53:56 字数 601 浏览 12 评论 0原文

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

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦断已成空 2024-09-21 19:53:56

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

如果您的文件是通过 include()require() 调用的,则会出现这种情况的差异。 exit 将终止程序,而 return 会将控制权返回给调用脚本(其中 includerequire被称为)。

Since you are using exit and return 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() or require(). exit will terminate the program, while return will take the control back to the calling script (where include or require was called).

明媚如初 2024-09-21 19:53:56

我倾向于使用 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.

月下客 2024-09-21 19:53:56

这取决于...如果您的脚本除了输出一条消息之外什么都不做,并且您不希望脚本随后执行任何操作,则 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.

倥絔 2024-09-21 19:53:56

Exit 与 die() 一样终止程序。 手册

Exit terminates the program like die(). manual

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文