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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With