Constants are, well, constant. At least that's the intent. Constants are supposed to be like that marvelous math construct "PI," or 3.14159265358979..., you know, it never comes out even, so how can that be a constant? I'm confused.
Anyway, with that note of confusion, what about constants in PHP. Constants are set in PHP and once set, are not supposed to be changed in the application. Usually they are used in configuration files. Something like the number of emails to send a registered user in one day. A number like 30 would be entered as a constant, and you could be assured your user would squeal like a stuck pig, of course, your sites traffic might suffer with that constant.
How do you set a constant in PHP. Since you only set it once, you have to "define" it, like so:
define ("NUMBER_OF_EMAILS", "30");
Pi would look like this:
define ("PI", "3.14159265358979...");
Of course, in this case, PI, used as a float would not work, as it is a string.
Seems simple enough, first is the word you want to use for the constant, and then the actual constant value.
Just so you're aware, whatever you call your constant is case sensitive. It is customary to use complete uppercase for the constant word, that way you know its a constant when you run into it in someone else's code. NUMBER_OF_EMAILS will give you 30, but number_of_emails will give you nothing, or an error message.
Why use constants as opposed to variables? Because constants can't be changed during the execution of the program, while variable can. So your assured that you'll send 30 emails and you won't be able to change that while the program is running, poor users.
And for those of you that are wondering the reason for this article, constants are easy. Well, PHP has a bunch of static and dynamic predefined constants, that there's a good chance we'll talk about in another article. I wanted to make sure we set a proper foundation first.