DEFINE vs Variable in PHP

Viewed 31044

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.

5 Answers

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.

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.

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

Related