为什么'defined()||定义常量时的define()语法 [英] Why 'defined() || define()' syntax in defining a constant

查看:231
本文介绍了为什么'defined()||定义常量时的define()语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在定义常量之前检查常量是否存在的方法:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆