A Single Article
Read it, comment, and share it with your friendsFor the love of all that is PHP, use constants
Let me show you something cool:
define("API_KEY", "afb8c982"); // ... echo("api key is: " . API_KEY);
If you haven’t seen that before, you need to get acquainted. Why do I insist? Because PHP developers have a habit of using global variables like they are bad words. Then they end up with two problems:
- Inside of functions & object methods, you have to declare the globals you want to use, or pass them in as arguments; always, all the time.
- Variables can always be changed, whether by accident or by a malicious hacker.
Plus, when they sell their applications to someone I work for, I have to deal with the messiness and the difficulty of declaring globals when what I’m working with are just what the name implies: constants that never change.
So, please, seriously, use PHP constants! They are defined just as so, at the beginning of you code:
define("ADMIN_NAME", "Mr. Montoya");
You can only set them to static data, like strings or numbers; not the result of functions or anything, and the name has to start with a letter. Then you call them without any delimiters. I capitalize them as a habbit to maintain a convention. Hope that helps.

Get a Trackback link
8 Comments
Responses to my articleWhy does no-one else ever mention these! Looks incredibly useful. Thanks Christian!
Constants are great, but they are unchangeable. So I sometimes use my custom “Storage” class that saves variables, and using a Sigleton pattern it’s global. What do you think about that, is it a good solution?
Good article
When I first got into PHP I used a lot of global variables, but have since switched over to constants. I keep going back through some of my old code and can’t believe how I used to right it. Embarrassing really.
Sjaq: Well, the point stands that they are for things that should never change. A storage object is OK, but I’ve never been too interested in using objects for data storage alone.
Ack, global abuse does need to go away. Constants are godsends for tweaking timer-based throttles, preset e-mail addresses, and other data that one doesn’t want to keep restating as “global” in every single function.
I whished all these open source projects would store the database info etc. in Constants…
I am proposing this since some time, but rarely nowhere I see that realised..
I use heredoc a lot and constants can’t be used in heredoc to my knowledge which puts me off using them.
Dean, I used to have that concern, but now I just pass the constants to variables before my HEREDOCs and move right along.
Leave a comment
Share your thoughts with the worldYou can use Markdown, or you can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>Please keep comments respectful and on topic.
This form is guarded by Akismet, so don't waste your time trying to submit spam. It won't work. Ever.