Alternative to keyword "or" in PHP

Now I have the following code:

stream_wrapper_register("var", "VariableStream") or die("Failed to register protocol"); 

And I want to do extra things before dying in the event of a function failure. Therefore, he raised this question:

How does the keyword 'or' work?

In many SO answers or answers, I saw people creating a function, for example:

 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 impractical in an object-oriented context, since I really don't want to create a method for this in my object, and I still cannot use closure.

So now I used this code, but I'm not sure if it will have the same behavior:

 if (!stream_wrapper_register("var", "VariableStream") { header('HTTP/1.1 500 Internal Server Error'); die("Failed to register protocol"); } 
+4
source share
5 answers

The "or" operator works because PHP-Interpreter is smart enough: Since the "or" connection is true, if the first one is true, it stops executing the instruction when the first is true.

Imagine the following code (PHP):

 function _true() { echo "_true"; return true; } function _false() { echo "_false"; return false; } 

now you can bind function calls and see what happens in the output:

 _true() or _true() or _true(); 

only "_true" will tell you, because the chain ends 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 continues.

The same thing works with "and"

You can also do the same with "and", with the difference that the "and" chain is complete when the first "false" occurs:

 _false() and _true() and _true(); 

will echo "_false" because the result is already completed and it can no longer be modified.

 _true() and _true() and _false(); 

will write "_true_true_false".

Because most of all functions indicate success, returning “1” to success and at level 0 you can do things like function() or die() . But some functions (in php quite rarely) return "0" to succes and! = 0 to indicate a specific error. Then you may have to use function() and die() .

+8
source
 a or b 

logically equivalent

 if (!a) { b } 

So your decision is ok.

+5
source

Similarly, since stream_wrapper_register() returns a boolean value.

+2
source

Two syntaxes are equivalent, and this is just a coding style / preference issue that you use. Personally, I don't like <statement> or die(...) , as in most cases it seems harder to read.

+2
source

The OR operator is available. sign ||

therefore, as an example, consider:

 <?php $count = NULL; if ($count == 0 || $count == NULL) { echo "\nNo Value!\n"; var_dump($count); } else { echo "\nSome Value"; } ?> 
0
source

Source: https://habr.com/ru/post/1394402/


All Articles