Sep
13

Constants: Programming 101

Author Chris Cummings    Category PHP     Tags

I’m not the smartest knife in the cookie jar and sometimes I forget my most basic of basics.  I was doing some PHP programming and here’s what I needed.  I needed a “variable” that was global but I didn’t want to have to reference it inside every function as global before I used it.  I racked my brain on what to do here.  This “variable” was not to change as what it was, was the root path of a site (http://www.site.com) and I knew my site would be moving at least once…every time I moved I didn’t want to update 40 references to “http://www.site.com/”.  What to do, what to do?

Finally I had an A-Ha moment…I started singing “Take On Me“.  Then after that I realized my answer was simple and something I probably hadn’t used in a bajillion years.  CONSTANTS!

For those that may have forgotten them a constant is sorta like a variable, but they never, ever, ever change once you set them.  that’s why they are CONSTANTS (as in constantly the same…ok, that’s a bit murky, scratch that…)

So here is how you define a constant in PHP:

define("HOWDY", "Hello world. ");

Simple, eh?
Here is how you use it (well, one example):

echo HOWDY . "How you doin?";

See? Easy-peezy.
Now go, use constants!

PS.  This is a PHP example, but you know constants are in pretty much every language.  Right?  Right!

Post comment

You must be logged in to post a comment.