John Squibb
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:
<?php
// Globally available database connection parameters
define('DATABASE_HOST', 'localhost');
define('DATABASE_USER', 'root');
define('DATABASE_PASSWORD', 'mypassword');
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;
Suggested Reading
Mastering Regular Expressions
by Jeffrey E.F. Friedl
This is a must-read for anyone interested in learning the complexities of regular expressions usage.
Make no mistake, this book is not a quick reference, but rather an all-in tome of regular expression goodness. Even if you only use the
occasional regex to validate emails, phone numbers, credit cards, or other, this book will give you an excellent understanding of how
regular expressions perform such tasks.
Suggested Reading
PHP Objects, Patterns, and Practice
by Matt Zandstra
Apress' PHP Objects, Patterns, and Practice is great for beginners and veterans alike.
The first several chapters focus entirely on the foundations of Object-Oriented PHP (OOPhp), while later chapters teach various patterns such as the Factory, Singleton, Observer, and more.
The author, Matt Zandstra, places major emphasis on good programming habits and strives to teach as many enterprise level practices as space allows.
The last chapters introduce the reader to a series of productivity tools which cover version control, documentation, automated builds, and unit testing.
This text will complement any OOPhp application developer, and I recommend it to anyone looking to dive in, or a seasoned OOPhp developer looking to pick up some new tricks and tools.
Tags: magic, numbers, class, constants, define, variable naming convention, PHP
Short URL: http://sqb.in/62t5