views:

37

answers:

3

Is there a benefit of using one over the other ?

$lang = isset($_COOKIE['lang']) ? $_COOKIE['lang'] : 'en';
# OR
define("LANG" , isset($_COOKIE['lang']) ? $_COOKIE['lang'] : 'en');

Thanks

+1  A: 

It depends on what you want to do. The value of the constant can't be change once it's defined. The variable can. This difference should make you choose the one you need.

Savageman
I got that - I meant performance-wise.
MotionGrafika
@MotionGrafika: Do you experience any performance problems? If not, choose the approach that fits better concept-wise.
Felix Kling
I haven't done any benchmarking test, constants do look nicer.
MotionGrafika
I didn't benchmark either, but I'm sure constants are better in term of performance (no scope / separate memory area). But I don't think that should be you're focus here. ;)
Savageman
+4  A: 

Constants:

  1. Cannot be changed afterwards.
  2. Are always in scope (in classes / functions / methods).
  3. Can only be scalars (or file-resources, but that's just an undocumented feature/bug)

Variables:

  1. Are changeable.
  2. May be out of scope.
  3. Can be any data.
Wrikken
I am aware of these - but from a user perspective - value won't change in the code once set / reset by the user.
MotionGrafika
You may be blessed with decent coworkers or your own project: coders can alter your variables when you least expect it...
Wrikken
+3  A: 

In this case a constant is more appropriate. As you want to use the same value through your entire application, and you don't want it possibly changed by mistake.

Do notice programing languages have many features you don't need to use to implement an algorithem, but rather they are there to make the algorithem more readable, maintainable and less prone to get bugs. Constants are one of those type of features.

Itay Moav