检查未定义的常量
我见过很多人使用
define('XXX') 或 Define('XXX', 'XXX');
而不是
if(!defined('XXX')){
define('XXX', 'XXX');
}
第一个代码做的事情完全相同吗?人们为什么使用它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
他们做同样的事情。第一个写起来比较短。与使用类似,
仅当左侧为
FALSE
时,才会计算逻辑OR
的右侧。They do exactly the same thing. The first is just shorter to write. Similar to using
The right side of the logical
OR
is evaluated only if the left side isFALSE
.做完全相同的事情。基本上是它的(真实条件)或错误选择
Does the exact same thing. Basically its (TRUE CONDITION) or FALSE ALTERNATIVE
它的作用完全相同,依赖于这样一个事实:如果第一个操作数的计算结果为 FALSE,则逻辑 OR 需要计算第二个操作数。
我不会太广泛地使用此方法,因为它倾向于“短路”条件(即 TRUE 或 f(); - f() 永远不会被调用)
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)该功能称为“短路评估”,对于许多语言来说都很常见。布尔表达式从左到右计算,当已经有结果时计算停止。在这种情况下,如果定义了常量,则无论其他项如何,表达式都为
TRUE
,因此 Define() 不会运行。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.