The Constant Gardener
The Constant Gardener

Reputation: 21

Checking for undefined constants

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?

Upvotes: 2

Views: 156

Answers (4)

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

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)

Upvotes: 0

Álvaro González
Álvaro González

Reputation: 146450

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.

Upvotes: 2

SeanCannon
SeanCannon

Reputation: 77966

Does the exact same thing. Basically its (TRUE CONDITION) or FALSE ALTERNATIVE

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270617

They do exactly the same thing. The first is just shorter to write. Similar to using

mysql_connect(...) or die('some error');

The right side of the logical OR is evaluated only if the left side is FALSE.

Upvotes: 1

Related Questions