tags:

views:

396

answers:

3

Can someone explain the difference between using

define('SOMETHING', true);

and

$SOMETHING = true;

And maybe the benefits between one or the other?

I use variables everywhere and even in a config type file that is included to everypage I still use variables as I don't see why to use the define method.

+3  A: 

Once defined, a 'constant' cannot be changed at runtime, whereas an ordinary variable assignment can.

Constants are better for things like configuration directives which should not be changed during execution. Furthermore, code is easier to read (and maintain & handover) if values which are meant to be constant are explicitly made so.

karim79
+9  A: 

DEFINE makes a constant, and constants are global and can be used anywhere. They also cannot be redefined, which variables can be.

I normally use DEFINE for Configs because no one can mess with it after the fact, and I can check it anywhere without global-ling, making for easier checks.

Chacha102
A: 

define() makes a read-only variable, compared to a standard variable that supports read and write operations.

just a note - i don't see how the term "read-only variables" applies to define() - as the manual states, it defines a *named constant*, which is something quite different.
jcinacio
-1: erroneous, and even if it were not it simply reiterates the above two posts.
hobodave
A constant is not a variable by definition (no pun intended) ;-)
Swish
@hobodave ... yeah, except that it was postet 1 hour BEFORE the "above" two posts ... apart from that, i don't see, how this is erroneous ... in many languages constants are readonly variables ... apart from the fact, that a "constant" is semantically more clear, it is more less interchangable with "read-only variable" ...
back2dos