developer tip

PHP에서 die ()와 exit ()의 차이점은 무엇입니까?

optionbox 2020. 10. 2. 22:03
반응형

PHP에서 die ()와 exit ()의 차이점은 무엇입니까?


PHP에서 die()exit()함수 의 차이점은 무엇입니까 ?

둘 다 동일한 기능을 가지고 있다고 생각하지만 둘 다 다른 점이있는 것 같지 않습니다. 무엇입니까?


차이가 없습니다. 동일합니다.

PHP 매뉴얼 exit:

참고 :이 언어 구성은 die().

PHP 매뉴얼 die:

이 언어 구조는 exit().


원산지의 차이

차이 die()exit()PHP에서 자신이다 기원 .


기능적으로 동일

die()하고 exit()있는 동일한 기능.

PHP 매뉴얼

PHP 매뉴얼 die:

이 언어 구조는 exit().

PHP 매뉴얼 exit:

참고 :이 언어 구성은 die().

함수 별칭 목록을 위한 PHP 매뉴얼 :

die 마스터 기능의 별칭입니다. exit()


다른 언어에서 다름

die()하고 exit()있는 다른 언어로 다른 하지만 PHP에서 그들은 동일합니다.

에서 또 다른 PHP의 호언 장담 :

... C 및 Perl 코더로서 저는 "왜 exit ()는 숫자 종료 상태로 프로그램을 종료하고 die ()는 오류 메시지를 stderr에 출력하고 EXIT_FAILURE 상태로 종료합니다. " 그러나 그때 나는 우리가 PHP의 복잡한 구문 영역에 있다는 것을 기억했습니다.

PHP에서 exit ()와 die ()는 동일합니다.

디자이너들은 분명히 "흠, C에서 exit ()를 빌려 보자 . Perl에서있는 그대로 die ()를 가져 오면 Perl 사람들은 아마 그것을 좋아할 것이다 . 웁스! 이제 두 개의 종료 함수가있다! 둘 다되도록 만들어 보자. 문자열이나 정수를 인자로 받아 동일하게 만들 수 있습니다! "

최종 결과는 이것이 실제로 일을 "더 쉽게"만들지 않고 더 혼란스럽게 만들 수 있다는 것입니다. C와 Perl 코더는 계속해서 exit ()를 사용하여 정수 종료 값만 던지고 die ()를 사용하여 오류 메시지를 던지고 실패로 종료합니다. 초보자와 PHP를 첫 번째 언어로 사용하는 사람들은 아마도 "음, 두 개의 종료 함수, 어떤 것을 사용해야합니까?"라고 궁금해 할 것입니다. 매뉴얼은 왜 exit ()와 die ()가 있는지 설명하지 않습니다.

일반적으로 PHP는 이와 같은 이상한 중복성을 많이 가지고 있습니다. 다른 언어 배경을 가진 사람들에게 친숙해 지려고하지만 그렇게하면서 혼란스러운 중복성을 만듭니다.


앞에서 언급했듯이이 두 명령은 동일한 파서 토큰을 생성합니다.

그러나

작은 차이가 있으며 파서가 토큰을 반환하는 데 걸리는 시간입니다.

PHP 파서를 연구하지 않았지만 "d"로 시작하는 긴 함수 목록과 "e"로 시작하는 짧은 목록 인 경우 "로 시작하는 함수 이름을 찾는 데 시간이 걸릴 것입니다. 이자형". 그리고 전체 함수 이름을 확인하는 방법에 따라 다른 차이가있을 수 있습니다.

PHP 구문 분석에 전념하는 "완벽한"환경과 다른 매개 변수를 가진 많은 요청이 없다면 측정 할 수 있을지 의문입니다. 그러나 차이점이 있어야합니다. 결국 PHP는 해석 언어입니다.


다이 에 대한 PHP 매뉴얼 :

die — exit와 동일

괄호를 사용하거나 사용하지 않고 die;같은 방식으로 수행 할 수도 있습니다 exit;.

선택의 유일한 이점 die()이상은 exit(), 당신이 여분의 문자를 입력에 여분의 시간이 될 수 있습니다 ;-)


다른 모든 정답으로 말한다, die그리고 exit동일 / 별칭이다.

Although I have a personal convention that when I want to end the execution of a script when it is expected and desired, I use exit;. And when I need to end the execution due to some problems (couldn't connect to db, can't write to file etc.), I use die("Something went wrong."); to "kill" the script.

When I use exit:

header( "Location: http://www.example.com/" ); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit; // I would like to end now.

When I use die:

$data = file_get_contents( "file.txt" );
if( $data === false ) {
    die( "Failure." ); // I don't want to end, but I can't continue. Die, script! Die!
}
do_something_important( $data );

This way, when I see exit at some point in my code, I know that at this point I want to exit because the logic ends here. When I see die, I know that I'd like to continue execution, but I can't or shouldn't due to error in previous execution.

Of course this only works when working on a project alone. When there is more people nobody will prevent them to use die or exit where it does not fit my conventions...


This page says die is an alies of exit, so they are identical. But also explains that:

there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script.

So, call me paranoid, but there may be no dieing in the future.


Here is something that's pretty interesting. Although exit() and die() are equivalent, die() closes the connection. exit() doesn't close the connection.

die():

<?php
    header('HTTP/1.1 304 Not Modified');
    die();
?>

exit():

<?php
    header('HTTP/1.1 304 Not Modified');
    exit();
?>

Results:

exit():

HTTP/1.1 304 Not Modified 
Connection: Keep-Alive 
Keep-Alive: timeout=5, max=100

die():

HTTP/1.1 304 Not Modified 
Connection: close

Just incase in need to take this into account for your project.

Credits: https://stackoverflow.com/a/20932511/4357238


This output from https://3v4l.org demonstrates that die and exit are functionally identical. enter image description here


They are essentially the same, though this article suggest otherwise.


Functionality-wise they are identical but I use them in the following scenarios to make code readable:

Use "die" when there is an error and have to stop the execution.

e.g. die( 'Oops! Something went wrong' );

Use "exit" when there is not an error and have to stop the execution.

e.g. exit( 'Request has been processed successfully!' );


When using command line,

 die("Error");

Will print to "Error" to STDOUT and exit with error code 0.

if you want to exit with error code 1, you have to:

  fwrite(STDERR, "Error");
    exit(1);

It could be useful while executing php scripts from command line or shell scripts and you want to see if the script terminated with a non zero exit code. copied answer of charanjeet from Quora


From what I know when I look at this question here

It said there that "in PHP, there is a distinct difference in Header output. In the examples below I chose to use a different header but for sake of showing the difference between exit() and die() that doesn't matter", and tested (personally)


die() and exit() both function are equivalent to each other. Main difference is exit() will stop the script but print output. But die() directly stop the execution of script.


Functionally, they are identical. So to choose which one to use is totally a personal preference. Semantically in English, they are different. Die sounds negative. When I have a function which returns JSON data to the client and terminate the program, it can be awful if I call this function jsonDie(), and it is more appropriate to call it jsonExit(). For that reason, I always use exit instead of die.


In w3schools Quiz: The die() and exit() functions do the exact same thing? my answer is false. That is incorrect answer. The right answer is true.

Here is the screenshot: enter image description here


Something I have noticed in my scripts at least is that exit() will stop the currently executing script and pass control back to any calling script, while die will stop php in its tracks. I would say that is quite a big difference?


The result of exit() function and die() function is allways same. But as explained in alias manual page (http://php.net/manual/en/aliases.php), it says that die() function calls exit function. I think it is hard coded like below:

function die($msg){
  exit($msg);
}

This is not a performance issue for small, medium and large projects but if project has billions multiply billions multiply billions processes, this happens very important performance optimization state.

But very most of people don't thinks this is a problem, because if you have that much processes, you must think more problem than if a function is master or alias.

But, exact answer is that; allways master function is more faster than alias.

Finally; Alias manual page says that, you may no longer use die. It is only an alias, and it is deprecated.

It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script. This list is provided to help those who want to upgrade their old scripts to newer syntax.


They sound about the same, however, the exit() also allows you to set the exit code of your PHP script.

Usually you don't really need this, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way.

Then you can use exit() and catch that later on. Die() however doesn't support that.

Die() always exists with code 0. So essentially a die() command does the following:

<?php
echo "I am going to die";
exit(0);
?>

Which is the same as:

<?php
die("I am going to die");
?>

참고URL : https://stackoverflow.com/questions/1795025/what-are-the-differences-in-die-and-exit-in-php

반응형