通过PHP中的AND运算符进行短路评估

通过PHP中的AND运算符进行短路评估

本文介绍了通过PHP中的AND运算符进行短路评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提高我的忍者h4x编码技能,并且我目前正在研究不同的框架,并且发现了很难用Google搜索的示例代码.

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.

我正在查看项目中使用的 FUEL框架.

I am looking at the FUEL framework used in a project.

我不了解的示例是

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

推荐答案

这是"短路评估的一种". and/&&表示比较的两端必须求和为TRUE.

This is a type of "short circuit evaluation". The and/&& implies that both sides of the comparison must evaluate to TRUE.

and/&&左侧的项目被评估为TRUE/FALSE,如果为TRUE,则右侧的项目将被执行和评估.如果左侧项目为FALSE,则执行暂停,并且右侧不进行评估.

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

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

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.

这篇关于通过PHP中的AND运算符进行短路评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:44