6

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.

4

5 回答 5

13

这是一种“短路评估”。这and/&&意味着比较的双方都必须评估为TRUE

左边的项目and/&&被评估为TRUE/FALSE,如果TRUE,右边的项目被执行和评估。如果左边的项目是FALSE,执行停止并且右边不被评估。

$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);

请注意,这些不一定是实际的 boolean TRUE/FALSE,但也可以是根据 PHP 评估规则的真值/假值。有关评估规则的更多信息,请参阅PHP 布尔文档

于 2011-10-05T17:19:35.027 回答
4

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).

于 2011-10-05T17:23:06.463 回答
2

这是一个有效的声明,工作方式如下:

如果 $data 有效(不是 ''、0 或 NULL)然后运行 ​​$this->template->set_global($data)

这是一种快速的说法:

if ($data)
{
    $this->template->set_global($data);
}

顺便说一句,您也可以使用&&而不是and

于 2011-10-05T17:21:21.403 回答
0

PHP 支持逻辑 AND 操作&&and它们通常工作相同,除了and运算符优先级略低于&&: http: //php.net/manual/en/language.operators.precedence.php

于 2011-10-05T17:27:33.343 回答
-2

它是一个布尔运算符,这意味着它需要两个操作数并返回一个布尔值——truefalse。如果两个操作数都计算为true(PHP 中除了空字符串、零或 null 之外的任何值),它将返回true,否则结果将为false.

这是 PHP 关于操作符的官方文档andhttp ://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
?>
于 2011-10-05T17:22:08.297 回答