Seeing the exit()
PHP documentation got me thinking:
$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
or exit("unable to open file ($filename)");
Couple questions:
exit()
?exit()
, how do you know to use it in some contexts vs. others? if/else
and or/exit
interchangeable? The exit() function prints a message and terminates the current script.
The exit() method is only used to exit the process. The die() function is used to print the message. The exit() method exits the script or it may be used to print alternate messages.
It means assign the key to $user and the variable to $pass. When you assign an array, you do it like this. $array = array("key" => "value"); It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.
Exit an if Statement With the Function Method in Python We can use an alternative method to exit out of an if or a nested if statement. We enclose our nested if statement inside a function and use the return statement wherever we want to exit.
In that context, the or
in that statement is one of PHP's logical operators which when used like that, will execute the second statement if and only if the first one fails due to short circuit evaluation.
Since fopen
returned false, the or exit
statement gets executed since the first part failed.
To understand it better, here is a quick explanation of short-circuit evaluation.
$x = 5;
$y = 42;
if ($x == 5 or $y == 42) {
echo "x or y is true";
}
In the above code, the expression $y == 42
is never evaluated because there is no need since the first expression was true.
In that example, they are using the same logic for deciding whether or not to evaluate the statement that calls exit
.
To address your questions:
exit
completely depends on the code you are writing. or exit
is just a bit shorter than using if/else
.Hope that helps.
exit()
or die()
in application code, since exceptions are preferred. However, I personally think you might be overcomplicating things a little bit... it kills script execution, so use it when you need to kill a script. Truthfully I mostly only ever kill scripts mid-execution when debugging (one-off breakpoints) and that's not ideal either (again exceptions do a better job).or
is mostly convenient. Here's an interesting point though... Why does
$resource = mysql_connect() || die('dead')
not work?
The answer is that the =
operator takes precedence over or
so that the assignment is made first like so: ($resource = mysql_connect()) or die()
. In this way its exactly like doing an if(!($resource = mysql_connnect())) { die() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With