PHP 中的 die() 和 exit() 函数

John Wachira 2023年1月30日
  1. 在 PHP 中使用 exit() 函数
  2. 在 PHP 中使用 die() 函数
PHP 中的 die() 和 exit() 函数

PHP 中的 die()exit() 函数具有相同的目的。语言构造 exit()die() 都输出一条消息并结束当前的 PHP 脚本。

本教程将研究 PHP 的 die()exit() 函数之间的区别。

在 PHP 中使用 exit() 函数

exit() 是一个内置函数,用于打印消息并退出 PHP 脚本。它非常适合因错误而终止执行。

语法:

exit("Type a Message Here");

  or

exit();

下面的示例代码说明了如何使用 exit() 函数结束执行。

代码片段:

<?php
$s = 300;
$v = 300.1;

if($s===$v){
  exit('The two are equal');
}else{
  exit ('The two are not equal');
}
 ?>

输出:

The two are not equal

exit() 函数退出脚本并打印消息 The two are not equal

在 PHP 中使用 die() 函数

die() 函数的工作方式类似于 exit() 函数。我们可以使用 die() 函数来检查错误并停止执行。

下面的示例说明了如何在发生错误时利用 die() 函数来结束数据库连接的执行。

代码片段:

<?php
$user = 'root';
$pass = '';
$db = 'sample tutorial';

$con = mysqli_connect("localhost", $user, $pass, $db);

if ($con->connect_error) {
  die("Connection failed: " . $con->connect_error);
}
?>

上面的代码没有输出。如果数据库连接不成功,那么 die() 函数将结束该过程。

如果连接成功,die() 函数会抛出异常,并且该函数不会结束进程。

exit() die()
无异常退出进程 可以抛出异常
退出脚本并打印消息 打印消息并结束进程
起源于 C 源自 Perl
作者: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

相关文章 - PHP Function