What does "or" do in the context of errors? - php

Reading this question I want to copy #Your Common Sense's error checking when using mysqli
$query="INSERT INTO testtable VALUES (23,44,56)";
$stmt_test->prepare($query);
$stmt_test->execute() or trigger_error($stmt_test->error);
$stmt_test->close();
How does or work? Another example of it's use is
$fh = fopen($myFile, 'w') or die("can't open file");
How is it different than using an if statment and would should it be used instead?

If the first statement returns false, then the second one is executed. That's it.

This is often how boolean "or" expressions are evaluated in programming languages. If you have a statement involving functions thus:
if (a() or b()) { ... }
then PHP works out that, if a() returns true, there is no need to evaluate the second function, since the overall result will be true regardless of the outcome of the second part. We can use this trick as a simple if mechanism:
(operation_that_might_fail() or report_error());
Here, I've removed the if around the clause. This will be evaluated just as before - except the result of ORing the two is then thrown away, since we don't need to do anything with it.
For this to work, operation_that_might_fail() must return boolean true on success, and false otherwise. As it happens, many PHP functions do exactly that, so we can often use this approach.
Side note: whilst the statement or is arguably clearer, PHP programmers tend to prefer the operator ||. Similarly, and will do what it says, but && is more common.

Related

PHP: Error handling with include

$file= #fopen("ssssss.php", r) or die("not found");
(#include("ssssss.php")) or die("not found");
In the first statement we don't put ( ) around #fopen and it is working fine.
But in the second if I didn't put these () it does't show any message.
so why with include I must round it with ( ) ?
I agree with the suggestions in the other answers but the actual answer to your question is this:
In the PHP documentation they say to take care when comparing the return value of include.
That's because it is a special construct and parentheses are not needed.
So when you do this (without wrapping parentheses):
#include("ssssss.php") or die("not found");
You're actually doing this, because or is evaluated first:
#include (("ssssss.php") or die("not found"));
Now, "ssssss.php" is a non empty string that evaluates logically to true.
or is a logical operator that gives true if any of the parameters is true (or both of them).
Also, this operator is short-circuit: if the first parameter is true, php already knows that the operator or will return true, so it doesn't waste time evaluating the second parameter, and die() is not executed.
So finally, or gives true and your sentence becames this:
#include (1);
Php tries to "include 1", and it would raise a warning but it does not because of the #.
Here you have a similar example in php.net.
Your first sentence is not the same case.
$file= #fopen("ssssss.php", r) or die("not found");
fopen is just a regular Php's function with its parentheses. Here you need to have in mind two operators: = and or.
= has higher precedence than or, so, if fopen's result is correctly assigned to $file (and it is), that operation will return true. And, as I explained before, "true or anything else", gives true but die() is not executed because of the short-circuit operator.
You should be using file_exists instead of using the # as the later covers all sorts of issues. A better solution would be...
if (file_exists("ssssss.php")) {
$file= #fopen("ssssss.php", r);
}
and
if (file_exists("ssssss.php")) {
include("ssssss.php");
}
That's not really a good use of include. If you need to include a php file and generate an error on failure, use require or require_once.
If you need to get the contents of the whole file, you could use file_get_contents().
Also, I agree with Nigel Ren about the use of # - it is a dangerous practice and should be avoided.

Assignment statement with AND operator

Can any one explain me following construct.
I do googling for this about 2 hours but can't understand.
public function __construct($load_complex = true)
{
$load_complex and $this->complex = $this->getComplex();
}
See: http://www.php.net/manual/en/language.operators.logical.php
PHP uses intelligent expression evaluation. If any of AND's operands evaluates to false, then there is no reason to evaluate other, because result will be false.
So if $load_complex is false there is no need to evaluate $this->complex = $this->getComplex();
This is some kind of workaround, but I do not suggest to use it, because it makes your code hard to read.
Specifically to your example $this->complex = $this->getComplex() if and only if $load_complex is set to true.
LIVE DEMO
NOTE: If any one of OPERAND result becomes 'false' in short
circuit AND evaluation means, the part of statement will be
OMITTED because there is no need to evaluate it.
Dont code like below line because, you may get probably logical
error while you are putting Expression instead of assigning values
to the variable on LEFT HAND SIDE...
$load_complex and $this->complex = $this->getComplex();
I have modified below with conditinal statement for your needs...
if($load_complex and $this->complex) {
$this->getComplex();
}

In PHP, why does "or die()" work, but "or return" doesn't?

In PHP, you can handle errors by calling or die to exit when you encounter certain errors, like this:
$handle = fopen($location, "r") or die("Couldn't get handle");
Using die() isn't a great way to handle errors. I'd rather return an error code so the parent function can decide what to do, instead of just ending the script ungracefully and displaying the error to the user.
However, PHP shows an error when I try to replace or die with or return, like this:
$handle = fopen($location, "r") or return 0;
Why does or die() work, but not or return 0?
I want to thank you for asking this question, since I had no idea that you couldn't perform an or return in PHP. I was as surprised as you when I tested it. This question gave me a good excuse to do some research and play around in PHP's internals, which was actually quite fun. However, I'm not an expert on PHP's internals, so the following is a layman's view of the PHP internals, although I think it's fairly accurate.
or return doesn't work because return isn't considered an "expression" by the language parser - simple as that.
The keyword or is defined in the PHP language as a token called T_LOGICAL_OR, and the only expression where it seems to be defined looks like this:
expr T_LOGICAL_OR { zend_do_boolean_or_begin(&$1, &$2 TSRMLS_CC); } expr { zend_do_boolean_or_end(&$$, &$1, &$4, &$2 TSRMLS_CC); }
Don't worry about the bits in the braces - that just defines how the actual "or" logic is handled. What you're left with is expr T_LOGICAL_OR expr, which just says that it's a valid expression to have an expression, followed by the T_LOGICAL_OR token, followed by another expression.
An expr is also defined by the parser, as you would expect. It can either be a r_variable, which just means that it's a variable that you're allowed to read, or an expr_without_variable, which is a fancy way of saying that an expression can be made of other expressions.
You can do or die() because the language construct die (not a function!) and its alias exit are both represented by the token T_EXIT, and T_EXIT is considered a valid expr_without_variable, whereas the return statement - token T_RETURN - is not.
Now, why is T_EXIT considered an expression but T_RETURN is not? Honestly, I have no clue. Maybe it was just a design choice made just to allow the or die() construct that you're asking about. The fact that it used to be so widely used - at least in things like tutorials, since I can't speak to a large volume of production code - seems to imply that this may have been an intentional choice. You would have to ask the language developers to know for sure.
With all of that said, this shouldn't matter. While the or die() construct seemed ubiquitous in tutorials (see above) a few years ago, it's not really recommended, since it's an example of "clever code". or die() isn't a construct of its own, but rather it's a trick which uses - some might say abuses - two side-effects of the or operator:
it is very low in the operator precedence list, which means practically every other expression will be evaluated before it is
it is a short-circuiting operator, which means that the second operand (the bit after the or) is not executed if the first operand returns TRUE, since if one operand is TRUE in an or expression, then they both are.
Some people consider this sort of trickery to be unfavourable, since it is harder for a programmer to read yet only saves a few characters of space in the source code. Since programmer time is expensive, and disk space is cheap, you can see why people don't like this.
Instead, you should be explicit with your intent by expanding your code into a full-fledged if statement:
$handle = fopen($location, "r");
if ($handle) {
// process the file
} else {
return 0;
}
You can even do the variable assignment right in the if statement. Some people still find this unreadable, but most people (myself included) disagree:
if ($handle = fopen($location, "r")) {
// process the file
} else {
return 0;
}
One last thing: it is convention that returning 0 as a status code indicates success, so you would probably want to return a different value to indicate that you couldn't open the file.
Return is fairly special - it cannot be anything like a function since it's a tool to exit functions. Imagine this:
if(1==1) return(); // say what??
If it was like this, return would have to be a function that does a "double exit", leaving not just its own scope but the caller's, too. Therefore return is nothing like an expression, it simply can't work that way.
Now in theory, return could be an expression that evaluates to (say) false and then quits the function; maybe a later php version will implement this.
The same thing applies to goto which would be a charm to work as a fallback; and yes, fallbacks are necessary and often make the code readable, so if someone complains about "clever code" (which certainly is a good point) maybe php should have some "official" way to do such a thing:
connectMyDB() fallback return false;
Something like try...catch, just more to the point. And personally, I'd be a lot happier with "or" doing this job since it's working well with English grammar: "connect or report failure".
TLDR: you're absolutely right: return, goto, break - none of them works. Easy to understand why but still annoying.
I've also stumbled upon that once. All I could find was this:
https://bugs.php.net/bug.php?id=40712
Look at the comment down below:
this is not a bug
I've searched in the documentation and I think it's due to the fact that return 0 is a statement whereas die() is essentially an expression. You can't run $handle = return 0; but $handle = fun(); is valid code.
Regarding error handling I would recommend custom codes or using custom handlers and triggers. The latter are described here for example.

Why if/else vs. or/exit in PHP?

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:
What are common use cases besides opening files for using exit()?
Since not every function everyone ever writes ends in exit(), how do you know to use it in some contexts vs. others?
Are if/else and or/exit interchangeable?
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:
I wouldn't use exit when opening a file failed unless the program was very specific. The better thing to do would be to log an error and then return the error to the caller so they can decide what to do.
When to use exit completely depends on the code you are writing.
Given the explanation about short-circuiting, yes they are interchangeable in that sense. Using or exit is just a bit shorter than using if/else.
Hope that helps.
CLI scripts, exit can take an integer parameter which is fed back to the console to indicate success or some form of error
I'm not inclined to use 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).
The use of 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() }
I tend to avoid using exit() at all as it's a really ugly way to handle errors from the user's perspective.
If you must use it, any non recoverable error would be a candidate. For example, database query or connection failures, or remote request failures.
if/else is equivalent to ...or whatever(). It's just a style thing, with the latter form being more succinct.
I would say you use exit in a situation where your code cannot continue if the function you were doing failed. For example reading a file that is needed.

php: usage of define

in Yii they use this code:
defined('YII_DEBUG') or define('YII_DEBUG',true);
i've never seen anyone write like this before (or). is this real php code or some syntax of yii?
Basically if defined("YII_DEBUG") evaluates to false, it will then define it. Kinda like:
mysql_connect() or die("DIE!!!!!");
It is actual PHP syntax, just not commonly used. It allows you to not have to write:
if(!defined("YII_DEBUG"))
{
define("YII_DEBUG", true);
}
or even shorter
if(!defined("YII_DEBUG"))
define("YII_DEBUG", true);
I'm guessing they used it to get rid of the if statement altogether. The second if statement without brackets would be a hazard for editing, and the first one might have taken up too much room for the developer.
Personally, I'd stick clear of this just because it isn't a commonly known feature. By using commonly known syntaxes (the if statements), other programmers don't have to wonder what it does.
(Although, I might now that I look at it. Seems straightforward and gets rid of unnessecary if clauses)
It's due to short circuit evaluation.
If defined('YII_DEBUG') returns false, it will try to evaluate the second expression to make the sentence true, defining YII_DEBUG constant as true.
The final result is that, if the constant were not defined, then define it as being true. If it's already defined (the value doesn't matter), then do nothing (as the first expression is true, the second expression does not need to be evaluated for the expression to be true).
Pretty straightforward - the 'or' operator is efficient in that it will only evaluate the second part of the statement if it needs to. So if the first part evaluates to true (the constant is already defined), then the define() call isn't executed.

Categories