Reputation: 11295
Right now I have the following code:
stream_wrapper_register("var", "VariableStream")
or die("Failed to register protocol");
And I want to do extra stuff before the die in case the function fail. So it raised that question :
How does the 'or' keyword works exactly ?
In many SO questions or answer, I've seen people creating a function, like this :
function doStuff() {
header('HTTP/1.1 500 Internal Server Error');
die("Failed to register protocol");
}
stream_wrapper_register("var", "VariableStream")
or doStuff();
... but this is kind of unpractical in an Object Oriented context as I don't really want to create a method for that in my object, and I can't yet use closure.
So for now, I've used this code, but I'm not sure that it will have the exact same behaviour :
if (!stream_wrapper_register("var", "VariableStream") {
header('HTTP/1.1 500 Internal Server Error');
die("Failed to register protocol");
}
Upvotes: 5
Views: 1673
Reputation: 1
THere an "OR" operator available. the sign is ||
hence, as an example consider:
<?php
$count = NULL;
if ($count == 0 || $count == NULL) {
echo "\nNo Value!\n";
var_dump($count);
} else {
echo "\nSome Value";
}
?>
Upvotes: 0
Reputation: 1969
The statement with "or" works, because the PHP-Interpreter is quite intelligent: Because a connection of "or"'s is true, if the first of them is true, it stops executing the statement when the first one is true.
Imagine following (PHP)code:
function _true() { echo "_true"; return true; }
function _false() { echo "_false"; return false; }
now you can chain the function calls and see in the output what happens:
_true() or _true() or _true();
will tell you only "_true", because the chain is ended after the first one was true, the other two will never be executed.
_false() or _true() or _true();
will give "_false_true" because the first function returns false and the interpreter goes on.
The same works with "and"
You can also do the same with "and", with the difference that a chain of "and"'s is finished, when the first "false" occurres:
_false() and _true() and _true();
will echo "_false" because there the result is already finished an cannot be changed anymore.
_true() and _true() and _false();
will write "_true_true_false".
Because most of all functions indicate their success by returning "1" on success and 0on error you can do stuff like function() or die()
.
But some functions (in php quite seldom) return "0" on succes, and != 0 to indicate a specific error. Then you may have to use function() and die()
.
Upvotes: 9
Reputation: 53563
a or b
is logically equivalent to
if (!a) {
b
}
So your solution is fine.
Upvotes: 5
Reputation: 28889
The two syntaxes are equivalent, and it's just a matter of coding style/preference as to which one you use. Personally, I don't like <statement> or die(...)
, as it seems harder to read in most circumstances.
Upvotes: 2
Reputation: 4311
It's exactly the same since stream_wrapper_register()
returns a boolean value.
Upvotes: 2