Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable or constant?

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

like image 744
MotionGrafika Avatar asked Jul 18 '10 22:07

MotionGrafika


3 Answers

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.

like image 112
Itay Moav -Malimovka Avatar answered Nov 01 '22 21:11

Itay Moav -Malimovka


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.
like image 24
Wrikken Avatar answered Nov 01 '22 19:11

Wrikken


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.

like image 1
Savageman Avatar answered Nov 01 '22 19:11

Savageman