1 (edited by RNilsson 2003-08-18 13:12)

Topic: Constants vs Variables

I've read up on constants today and my first q is; why?
What can a constant do that a variable can not?

Some of the stuff i (think i) have come up with so far:

Constant is global by defaul, variable is not unless you $GLOBALS['variable'].
Constants can not be overridden, ie you can not name a constant the same in two different parts of the script (due to their globalness?), meanwhile variables can be overridden.
You can get a list of all defined constants, as with variables you can not (unless $GLOBALS can be used?)

EDIT: I cant find a way to undefine constants...Is there one?

What scope of usage do constants deserve?
Only tru variables that is used throughout the site/app like Directory-locations, hostinfo for db's etc etc.

So, folks, why sould i use or not use constants, and most importantly, for what should constants be used for?

Re: Constants vs Variables

unset() can undefine $GLOBALS['variable'] so it should undefine constants too, but i haven't tested it.

3 (edited by RNilsson 2003-08-18 17:26)

Re: Constants vs Variables

Now when i have read some more i found " You can define a constant by using the define()-function. Once a constant is defined, it can never be changed or undefined." here under syntax: http://se2.php.net/manual/en/language.constants.php

EDIT: Sorry, slipped into swedish-mode...Fixed.

Re: Constants vs Variables

Well, the fundamental difference, which I see you discovered yourself, is that constants store constant values and variables store variable values :P

"Programming is like sex: one mistake and you have to support it for the rest of your life."

Re: Constants vs Variables

Yeah, most of the time i tend to read up on anything new so i at least know a little about what i am about to wreck havoc on smile

But, since i have some importand site-wide variables in my config.inc.php-file in an array-style, which is already included in the top of every "public" file, i don't really see the point of using constants for anything else then for, let's say, the base_url, dbinfo etc as those are used inside functions, objects and evals in a different way then just storing values.

Other then that, i have pretty much no ideas for it's use...

6

Re: Constants vs Variables

RNilsson wrote:

i have some importand site-wide variables in my config.inc.php-file in an array-style, which is already included in the top of every "public" file

If those site-wide variables stay the same then they are constants as they will be the same on every page.

E.g. 5 is a constant since it has only a value of 5 (In most cases).
      X on the other hand could be a variable since it could have the value 5 or 9.

Arkus

Re: Constants vs Variables

I've worked out a pretty good usage of constants vs variables for certain configitems like dbhost, username etc

Re: Constants vs Variables

Good information on this thread.