Constants? Well, I declare!

Feb 05 2007

In Essential PHP Security (p. 16), Chris Shiflett writes “A variable is just a container for … data, and it can always be overwritten later in the script with tainted data. Of course, this is why [it] is called a variable. If you don’t want the data to change, use a constant instead.”

I guess I thought a variable earned its name more from its variability than its changeability, but on the conclusion, Chris and I agree: any value that has no reason to change over the course of a program’s execution ought to be declared as constant.

It might seem pointlessly thorough to declare a variable as constant when it is known by the programmer to be utilized only in a read-only fashion, but if multiple programmers are working as a team, or if code will one day be maintained by a different engineer (which is likely), the only way to make reasonably sure someone won’t accidentally reuse a sensitive variable is for someone to make a list of variables already in use. And if you’re going to be making a list, you might as well make it a list of constants and include it in the code, which offers the added advantage of actually preventing accidental reuse, not just creating documentation nobody has time to read anyway.

Most people who have worked with a substantial amount of team code can probably identify with the frustration of adding some code that mysteriously breaks the application in a way that’s completely unrelated to the change, only to find out it was a variable used twice. I wouldn’t say this is an every day kind of problem (or I wouldn’t be mentioning it), but it is a high risk problem: if someone you trusted told you that somewhere in your code was a supposedly single-use variable being used twice, would you try to find it and fix it? Of course, because it would represent an unknown with a potentially dangerous downside.

Another benefit: it makes you think about what you’re going to be doing with a variable.

Finally, if you’re still unconvinced, check out PHP Language Reference : Chapter 13. Constants. It’s easy!

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Slashdot
  • Digg
  • del.icio.us
  • Reddit
  • digg
  • Technorati
  • StumbleUpon

Related posts:

  1. McGovern and Hoff on Mistakes
  2. Looking for things to worry about?
  3. ISO 27001 Standard Released
  4. The Convention on Cybercrime: Why It Will Do Far More Harm Than Good
  5. Analyze This and That - the Network Tells All

Posted by Benjamin Field on Monday, February 5th, 2007, at 6:00 am, and filed under Articles.

Follow any responses to this entry with the RSS 2.0 feed.

You can post a comment, or trackback from your site.