Checking for undefined constants - php

I've seen a lot of people using
defined('XXX') or define('XXX', 'XXX');
instead of
if(!defined('XXX')){
define('XXX', 'XXX');
}
Does the first code do exactly the same thing? Why do people use it?

The feature is called short circuit evaluation and it's common to many languages. Boolean expressions are evaluated from left to right and evaluation stops when there's already a result. In this case, if the constant is defined the expression is TRUE no matter the other term, so define() does not run.

They do exactly the same thing. The first is just shorter to write. Similar to using
mysql_connect(...) or die('some error');
The right side of the logical OR is evaluated only if the left side is FALSE.

Does the exact same thing. Basically its (TRUE CONDITION) or FALSE ALTERNATIVE

It does exactly the same, relying on the fact that logical OR requires evaluation of the second operand if the first evaluates to FALSE.
I wouldn't use this method too broadly, as it tends to "short-circuit" conditionals (i.e. TRUE or f(); - f() will never be called)

Related

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();
}

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

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.

false / FALSE — any difference?

I noticed that some PHP frameworks use exclusively lowercase true/false and others upper.
Does it make any difference at all? I for one prefer lowercase.
No difference, some people consider FALSE to be a constant and thus use the old screaming caps notation.
It's been some time but because this is the first search result for the query I thought this info would be useful.
According to the PSR-2 Coding Style Guide
PHP keywords MUST be in lower case. The PHP constants true, false,
and null MUST be in lower case.
Even though you can use the screaming caps notation; if you are trying to follow these guidelines you should be doing it in lowercase. There will be no functional difference either way.
I know I'm late to the party here, but I'll just quote the documentation in case anybody wants an authoritative answer, as I did.
To specify a boolean literal, use the constants TRUE or FALSE. Both are case-insensitive.
In fact, the example immediately following the above uses this fact:
$foo = True; // assign the value TRUE to $foo
PhP is biZarRe.

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.

if statement condition optimisation

I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false.
if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed?
if ( (condition1) | (condition2) ){
// do this
}
or would I need to nest two if statements to only check the second condition if the first evaluates to false?
if (condition1){
// do this
}else if (condition2){
// do this
}
I am working in PHP, however, I assume that this may be language-agnostic.
For C, C++, C#, Java and other .NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated.
An old trick for doing obfuscated code was to use this to create if statements, such as:
a || b();
if "a" is true, "b()" would never be evaluated, so we can rewrite it into:
if(!a)
b();
and similarly:
a && b();
would become
if(a)
b();
Please note that this is only valid for the || and && operator. The two operators | and & is bitwise or, and and, respectively, and are therefore not "optimised".
EDIT:
As mentioned by others, trying to optimise code using short circuit logic is very rarely well spent time.
First go for clarity, both because it is easier to read and understand. Also, if you try to be too clever a simple reordering of the terms could lead to wildly different behaviour without any apparent reason.
Second, go for optimisation, but only after timing and profiling. Way too many developer do premature optimisation without profiling. Most of the time it's completely useless.
Pretty much every language does a short circuit evaluation. Meaning the second condition is only evaluated if it's aboslutely necessary to. For this to work, most languages use the double pipe, ||, not the single one, |.
See http://en.wikipedia.org/wiki/Short-circuit_evaluation
In C, C++ and Java, the statement:
if (condition1 | condition2) {
...
}
will evaluate both conditions every time and only be true if the entire expression is true.
The statement:
if (condition1 || condition2) {
...
}
will evaluate condition2 only if condition1 is false. The difference is significant if condition2 is a function or another expression with a side-effect.
There is, however, no difference between the || case and the if/else case.
I've seen a lot of these types of questions lately--optimization to the nth degree.
I think it makes sense in certain circumstances:
Computing condition 2 is not a constant time operation
You are asking strictly for educational purposes--you want to know how the language works, not to save 3us.
In other cases, worrying about the "fastest" way to iterate or check a conditional is silly. Instead of writing tests which require millions of trials to see any recordable (but insignificant) difference, focus on clarity.
When someone else (could be you!) picks up this code in a month or a year, what's going to be most important is clarity.
In this case, your first example is shorter, clearer and doesn't require you to repeat yourself.
According to this article PHP does short circuit evaluation, which means that if the first condition is met the second is not even evaluated.
It's quite easy to test also (from the article):
<?php
/* ch06ex07 – shows no output because of short circuit evaluation */
if (true || $intVal = 5) // short circuits after true
{
echo $intVal; // will be empty because the assignment never took place
}
?>
The short-circuiting is not for optimization. It's main purpose is to avoid calling code that will not work, yet result in a readable test. Example:
if (i < array.size() && array[i]==foo) ...
Note that array[i] may very well get an access violation if i is out of range and crash the program. Thus this program is certainly depending on short-circuiting the evaluation!
I believe this is the reason for writing expressions this way far more often than optimization concerns.
While using short-circuiting for the purposes of optimization is often overkill, there are certainly other compelling reasons to use it. One such example (in C++) is the following:
if( pObj != NULL && *pObj == "username" ) {
// Do something...
}
Here, short-circuiting is being relied upon to ensure that pObj has been allocated prior to dereferencing it. This is far more concise than having nested if statements.
Since this is tagged language agnostic I'll chime in. For Perl at least, the first option is sufficient, I'm not familiar with PHP. It evaluates left to right and drops out as soon as the condition is met.
In most languages with decent optimization the former will work just fine.
The | is a bitwise operator in PHP. It does not mean $a OR $b, exactly. You'll want to use the double-pipe. And yes, as mentioned, PHP does short-circuit evaluation. In similar fashion, if the first condition of an && clause evaluates to false, PHP does not evaluate the rest of the clause, either.
VB.net has two wonderful expression called "OrElse" and "AndAlso"
OrElse will short circuit itself the first time it reaches a True evaluation and execute the code you desire.
If FirstName = "Luke" OrElse FirstName = "Darth" Then
Console.Writeline "Greetings Exalted One!"
End If
AndAlso will short circuit itself the first time it a False evaluation and not evaluate the code within the block.
If FirstName = "Luke" AndAlso LastName = "Skywalker" Then
Console.Writeline "You are the one and only."
End If
I find both of these helpful.

Categories