I am trying to understand the below code but I am confused by the use of the &&
operator.
Please explain the purpose of the &&
operation in the following code
function getErrors($autoClean=TRUE) {
$retVal = $this->getErrorMessages();
$autoClean && $this->unsetErrorMessages();
return $retVal;
}
Here, &&
acts as a short-circuit operator (see also the code example here).
$autoClean
evaluates to true
, $this->unsetErrorMessages()
will be executed.$autoClean
evaluates to false
, $this->unsetErrorMessages()
will not be executed.Using ||
instead of &&
would reverse this behavior.
The same behavior can obviously also be achieved by adding an additional if
statement. In doing so:
a && b()
can be rewritten as
if (a) {
b();
}
a || b()
can be rewritten as
if (!a) {
b();
}
While the use of short-circuit operators can reduce the number of lines, it can also make code harder to read.
In terms of execution speed, there should be no noticeable difference.
Update
I have to retract my earlier statement about there being no noticeable difference in execution speed. Given the following two test scripts, i.e. a version with the short-circuit operator:
<?php
$a = true;
function b() { global $a; $a = !$a; }
for ($i = 0; $i < 10000000; $i++) {
$a && b();
}
?>
And a version with an if
statement:
<?php
$a = true;
function b() { global $a; $a = !$a; }
for ($i = 0; $i < 10000000; $i++) {
if($a) { b(); }
}
?>
It turns out that the second version (with the if
statement) is roughly 40% faster (~450ms vs. ~750ms) on my PHP 5.5.9 version running on Ubuntu 14.04 LTS (64 bit).
Results may vary for different PHP versions and operating systems, but at least on my machine I consistently notice a significant difference in execution speed.
Here, &&
acts as a short-circuit operator as told by @robby.
The line provides us a behaviour to prevent default execution of any code
and also provides us facility to reduce lines of code
as
$autoClean && $this->unsetErrorMessages();
will be equivalent to
if($autoClean){
$this->unsetErrorMessages();
}
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