为什么'defined()||定义常量时的define()语法 [英] Why 'defined() || define()' syntax in defining a constant
问题描述
为什么在定义常量之前检查常量是否存在的方法:
defined('CONSTANT') || define('CONSTANT', somedefinition);
用于代替:
if !(defined('CONSTANT')) {
define('CONSTANT', somedefinition);
}
使用或"代替"||"有什么区别吗?在第一种方法中,我在书中都看到了.
由于|| (在C,Java,C#,php中)被短路"(如果第一个操作数为true,则不对第二个操作数求值,因为无论第二个表达式是什么,表达式都已经被计算为真.>
因此,这是经典的C风格简洁".即使使用的代码与使用更长的代码完全一样,也应使用尽可能少的代码行.
因此它显示为:如果已定义(...),请不要执行define()位... 如果未定义,请尝试评估define()位,并在此过程中定义常量.
Why is this method of checking if a constant exist before defining it:
defined('CONSTANT') || define('CONSTANT', somedefinition);
used instead of:
if !(defined('CONSTANT')) {
define('CONSTANT', somedefinition);
}
Is there any difference in using 'or' instead of '||' in the first method, I have seen both in books.
Due to the || being (in C, Java, C#, php) being "short-circuited" (if the first operand is true, the second is not evaluated because the expression has already been evaluated to be true, no matter what the second is.
So this is classic C-style "brevity" in action. Use as fewer lines of code as possible, even though its doing exactly the same as something more longhand.
So it reads: if defined(...), don't do the define() bit... if not defined(), do try to evaluate the define() bit and in the process, it'll define the constant.
这篇关于为什么'defined()||定义常量时的define()语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!