Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP -What's the difference between global variables and constants

According to many sources, register_globals (global variables that is) should be disables in your php.ini. Should I write define() in my code and use constants if global variables are disabled? Are those even related?

like image 465
Gal Avatar asked Jan 13 '10 20:01

Gal


People also ask

What is the difference between a constant and a global variable?

Global variables aren't constant (you can change the value of a global variable, but you can only define a constant once). Constants aren't always global (you can declare a constant in a class). Also, global variables can be any type: scalar, array, or object. Constants can only be scalars.

Are constants global in PHP?

PHP constants are said to have global scope. This basically means that once you have defined a constant it is accessible from any function or object in your script.


1 Answers

They are related in that they have global scope, but constants are meant to not change once defined, unlike global variables which the page can modify as it goes along. So just switching over to using define() instead of a global won't help much.

It's better if you refactor your methods to take the variables as parameters and rely on that to pass variables around.

like image 142
Parrots Avatar answered Nov 03 '22 04:11

Parrots