“ Do something OR DIE()”在 PHP 中是如何工作的?

我正在编写一个 php 应用程序来访问 MySQL 数据库,在一个教程中,它介绍了一些形式

mysql_connect($host, $user, $pass) or die("could not connect");

PHP 如何知道函数失败以便运行骰子部分?我想我问的是“或者”是怎么回事。我以前没见过。

103898 次浏览

If the first statement returns true, then the entire statement must be true therefore the second part is never executed.

For example:

$x = 5;
true or $x++;
echo $x;  // 5


false or $x++;
echo $x; // 6

Therefore, if your query is unsuccessful, it will evaluate the die() statement and end the script.

PHP's or works like C's || (which incidentally is also supported by PHP - or just looks nicer and has different operator precedence - see this page).

It's known as a short-circuit operator because it will skip any evaluations once it has enough information to decide the final value.

In your example, if mysql_connect() returns TRUE, then PHP already knows that the whole statement will evaluate to TRUE no matter what die() evalutes to, and hence die() isn't evaluated.

If mysql_connect() returns FALSE, PHP doesn't know whether the whole statement will evaluate to TRUE or FALSE so it goes on and tries to evalute die() - ending the script in the process.

It's just a nice trick that takes advantage of the way or works.

It works as others have described.

In PHP, do not use "die", as it does NOT raise an exception (as it does in Perl). Instead throw an exception properly in the normal way.

die cannot be caught in PHP, and does not log - instead it prints the message ungracefully and immediately quits the script without telling anybody anything or giving you any opportunity to record the event, retry etc.

If you would like to add more code if the connection doesn't work, beyond a die statement:

$con=mysql_connect($host, $user, $pass)
if(!$con)
{
// ... add extra error handling code here
die("could not connect");
}
else
{
echo "Connected";
}