Overcoming Magic Numbers Through the Use of Constants
Magic Numbers, called Magic Constants by some (at risk of association with PHP's so-called magic constants), are unnamed numerical constants that appear directly in code, inhibiting the reader from immediately understanding the intended purpose of the value. They litter the best of code, and often creep in with quick modifications, one-offs, tweaks, and so forth. The good news is, Reducing them can be as easy as adding a few extra variable declartions. For developers using Object-Oriented PHP, class constants can provide a quick and easy escape from the evil, universe-imploding doominess of Magic Numbers.
Declaring class constants is easy:
- class My_Class
- {
- const MY_CONSTANT = 1;
- }
Why use Constants?
Class constants are great for applying meaningful names to numerical values used throughout code, in a single location. They greatly improve the readability of the code, and save the maintainer from having to hunt about the document in search of various values. Best of all, if a value needs updating, it needs updating in only one spot!
By convention, constants appear in uppercase characters only, though, this is entirely up to you, your conventions, and your particular implementation.
I like to use constant names that convey their purpose. For example, suppose we were writing an email class that needed to flag messages stored in a database with various statuses. We might have a different constant for each step of the process:
- class Emailer
- {
- // Email transmission statuses
- const STATUS_QUEUED = 0;
- const STATUS_SENT = 1;
- const STATUS_BOUNCED = 2;
- const STATUS_REPLY_RECEIVED = 3;
- //etc...
- }
throughout the code we merely refer to our constants like so:
- private function send(Message $message)
- {
- // Send logic here....
- // Now, update status in database
- $this->database->set_message_status($message->id, self::STATUS_SENT);
- }
Constants Outside of Classes
For procedural scripts, there's still hope for preventing magical values: the almighty define(). Following the same conventions outlined above, use the define() function to declare global values that will help reduce obfuscated values throughout your code.
For example:
As of PHP 5.3.0, you can use the const keyword outside of a class. See http://us3.php.net/const for syntax and usage examples.
Final Thoughts
Using constants can make code much easier to read, and helps add to its maintainability. However, never allow constants to replace proper commenting and variable naming conventions! Well-documented code and meaningful variable names are essential components in any code that is to be reused or maintained by others.
I'd take this code:
- // Area is determined by multiplying the length of an object by its width.
- $length = 10;
- $width = 20;
- $area = $length * $width;
over this code any day:
- $a = My_Class::L * My_Class::W;




