當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


PHP die()和exit()的區別用法及代碼示例

exit()在 PHP 中,exit()函數打印一條消息並退出應用程序。它通常用於在發生錯誤時打印不同的消息。使用exit()當沒有錯誤並且必須停止執行時。

用法:

exit("Message goes here");
or
exit();

例子:

exit("This request is processed");

程序1:

PHP


<?php
   exit ("This is an exit function in php");
   echo "This will not printed because "
    . "we have executed exit function";
?>

輸出:

This is an exit function in php

程序2:

PHP


<?php
  $a = 10;
  $b = 10.0;
  if($a == $b) {
    exit('variables are equal');
  }
  else {
    exit('variables are not equal'); 
  }
?>

輸出:

variables are equal

die() 在 PHP 中,die()是相同的exit()。程序的結果將是一個空屏幕。使用die()當出現錯誤並且必須停止執行時。

用法:

die("Message goes here"); 
or 
die();

例子:

die('Oops! Something went wrong');

程序:

PHP


<?php
    $num = 1;
    // die can only print string values,
    // hence there will be no output
    die($num);
?>

輸出:

No Output

注意:上述程序的輸出將是一個空屏幕,因為它類似於exit(),die()隻能打印字符串值。

die()和exit()函數的區別:

die()

exit()

die()方法用於拋出異常 exit()方法僅用於退出進程。
die()函數用於打印消息。 exit() 方法退出腳本,或者可用於打印替代消息。
該方法來自 Perl 中的die()。 該方法來自C中的exit()。


相關用法


注:本文由純淨天空篩選整理自sanketnagare大神的英文原創作品 Difference between die() and exit() functions in PHP。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。