问题
I'm trying to improve my coding ninja h4x skills, and I'm currently looking at different frameworks, and I have found sample code that's pretty hard to google.
I am looking at the FUEL framework used in a project.
The sample I don't understand is
$data and $this->template->set_global($data);
What is the and keyword doing in this line of code? It is used many places in the framework and it's the first that I have found that uses it.
回答1:
This is a type of "short circuit evaluation". The and/&&
implies that both sides of the comparison must evaluate to TRUE
.
The item on the left of the and/&&
is evaluated to TRUE/FALSE
and if TRUE
, the item on the right is executed and evaluated. If the left item is FALSE
, execution halts and the right side isn't evaluated.
$data = FALSE;
// $this->template->set_global($data) doesn't get evaluated!
$data and $this->template->set_global($data);
$data = TRUE;
// $this->template->set_global($data) gets evaluated
$data and $this->template->set_global($data);
Note these don't have to be actual boolean TRUE/FALSE
, but can also be truthy/falsy values according to PHP's evaluation rules. See the PHP boolean docs for more info on evaluation rules.
回答2:
When you use logical operators, operands (the value on the left and the value on the right) are evaluated as boolean, so basically that code will do this, in a shorter way:
$o1 = (Bool)$data; // cast to bool
if($o1)
$o2 = (Bool)$this->template->set_global($data); // cast to bool
Edit:
Some additional information:
$a = 33;
isset($a) && print($a) || print("not set");
echo "<br>";
isset($a) AND print($a) OR print("not set");
echo "<br>";
Try to comment/decomment $a = 33;
. This is the difference between &&
and AND
, and between ||
and OR
(print
returns true that is casted to "1" when converted to string).
回答3:
It is a valid statement and works like this:
If $data is valid (is not '', 0 or NULL) then run $this->template->set_global($data)
It's a quick way of saying:
if ($data)
{
$this->template->set_global($data);
}
Btw you can also use &&
instead of and
回答4:
PHP supports both &&
and and
for the logical AND operation, and they generally work identically, except and
has a slightly lower operator precedence than &&
: http://php.net/manual/en/language.operators.precedence.php
回答5:
It's a boolean operator which means it takes two operands and returns a boolean value-- true
or false
. If both operands evaluate to true
(anything but and empty string, zero or null in PHP) it will return true
, otherwise the result will be false
.
Here's PHP's official docs on the and
operator: http://www.php.net/manual/en/language.operators.logical.php
<?php
$a = true and false; # FALSE
$b = true and 5; # TRUE
$c = '' and 0; # FALSE
$d = null and true; # FALSE
?>
来源:https://stackoverflow.com/questions/7665101/short-circuit-evaluation-via-the-and-operator-in-php