Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 'defined() || define()' syntax in defining a constant

Tags:

php

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.

like image 651
David Casillas Avatar asked Aug 10 '11 09:08

David Casillas


2 Answers

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.

like image 147
4 revs, 4 users 79% Avatar answered Oct 26 '22 08:10

4 revs, 4 users 79%


Others have answered first part of your question, so I'll take the latter:

As far as or vs || is concerned there is no difference in this specific case. However, or has lower operator precedence than = (assignment operator), while || has higher. This is significant, if you want to use short-circuiting to do assignment.

Consider:

$a = 2 or $b = 2;
var_dump($a);  // int(2)


$a = 3 || $b = 3;
var_dump($a);  // bool(true)

In second example, || got evaluated before =. Using parentheses it would look like this

$a = (3 || $b = 3);

while the first one

($a = 2) or ($b = 2);
like image 36
Mchl Avatar answered Oct 26 '22 08:10

Mchl