Constant $GLOBAL-isation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Constant $GLOBAL-isation

Post by McGruff »

I've ignored constants up till now, but after another look, I'd be interested if someone could confirm the points below.

It seems that you can often do the same sort of thing using either constants or global vars. There may be some security advantages with constants though:

(1) An undefined constant will produce an error message - not so an undefined var, although I suppose that depends on error reporting settings.

(2) You cannot have an unset constant once it's been defined (obviously), but you could refer to a global var within a function without adding it to the scope - a possible substitution loophole.

(3) Also, constants cannot be redefined - another bit of protection from variable substitution (a global var added to a function scope could possibly be overwritten by a forged $_POST var, I think, if you do the $$key = $value thing).

(4) Using constants rather than global vars could give leaner code, ie no need for endless $GLOBAL[]-isation inside a function scope.

(5) BUT: is it more efficient to declare a var rather than run the define() function to declare a constant?

Final note from manual:

"Constants are limited to scalar values - ie those containing an integer, float, string or boolean. Arrays, objects and resources cannot be defined as constants."
Post Reply