PHPWomen Site Home » Programming » Best Practices » Guess the magic number: Using constants effectively in PHP
Guess the magic number: Using constants effectively in PHP [message #1280] Sat, 02 June 2007 06:41 Go to next message
KathyReid  is currently offline KathyReid
Messages: 224
Registered: October 2006
Location: Geelong, Victoria, Austra...
Member
How many of us have been maintaining code written by other developers when we see something like this;

<?php
if($variable == 42){
    echo 
'I know the meaning of life!;
} elseif ($variable == 144) {
    echo '
Thats gross!';
} elseif ($variable == 1024){
    echo '
I am a kilobyte';
}
?>


This style of coding, where value comparisons are done using hard-coded values, is called 'magic numbers'. Magic numbers is poor programming practice for a number of reasons;

  • Using hard coded is values is fine where the code will never be extended, maintained or added to. Fortunately, most of us live in the real world, where code is continually updated. Over time you are likely to forget what the magic numbers mean, and you will have to spend several hours reviewing code to remember.
  • If you have used similar value comparisons in multiple places in your code, then it is difficult and error prone to update them if the value of a magic number changes.
  • Magic numbers do not help the readability of your code - often several comments are required to explain what the magic numbers mean.


So, what can we use instead of Evil Magic Numbers that will afflict your code with pestilence?

The answer is: Constants!

Constants are your friend. They will bring you chicken soup when you are ill. They will be your shoulder to cry on. OK, not really but they are very useful. Let's see why.

Using the example above, let's see how constants can make the code very readable, and easily maintained;

<?php
define
('MEANING_OF_LIFE'42);
define('GROSS'144);
define('KILOBYTE'1024);

if(
$variable == MEANING_OF_LIFE){
    echo 
'I know the meaning of life!;
} elseif ($variable == GROSS) {
    echo '
Thats gross!';
} elseif ($variable == KILOBYTE){
    echo '
I am a kilobyte';
}
?>


The code in this example is much more readable and easily understood. What would happen if the meaning of life changed? We would only need to update it in one place, not in several places throughout the code.

Quote:

The only practice that's now constant is the practice of constantly accommodating to change. Mcgovern, William


A little on constants

Constants in PHP are special types of variables that are set once and hold the same value for the lifetime of a script, in contrast to variables. Scope rules for variables apply to constants. One very useful feature of constants is that they can be 'included'.


Although constants in PHP can be named in lower-case, industry practice, and other coding language practice, is to name constants in upper case. Constants can contain letters, numbers and the underscore [_] character. They should be named starting with a letter.

Constants can only be used to define simple data types such as integers. floats and boolean values. For instance, you cannot define a file handler or database connections as a constant (or any other resource type).

They are reference in code without quotation marks (ie MY_CONSTANT instead of 'MY_CONSTANT', and not $MY_CONSTANT).


<?php
// valid constant definitions
define ('MY_FIRST_CONSTANT''Little Bo Peep lost her sheep');
define ('MY_2ND_CONSTANT''Little Bo Peep is negligent');
define ('A_BOOLEAN_CONSTANT'TRUE);
define ('A_FLOAT_CONSTANT'123.456);

// invalid constant definitions
define('3RD_CONSTANT''Little Bo Peep should be referred to as Bo Peep who  is of less than average stature'); 
// this is not valid because it starts with a number

define('FOURTH_CONSTANT'fopen('myfile.txt'"R");
// resources cannot be defined as constants
?>



For more information on constants, please see;
http://au2.php.net/manual/en/language.constants.php
Re: Guess the magic number: Using constants effectively in PHP [message #1281 is a reply to message #1280 ] Sun, 03 June 2007 03:23 Go to previous messageGo to next message
lorna  is currently offline lorna
Messages: 413
Registered: October 2006
Location: Leeds, UK
Feeling Comfortable

Great article Smile This is a very good "best practice" point and well-written. I especially love the Bo Peep references!! Its good to see we haven't forgotten about our best practices forum, I was starting to worry.


Lorna Mitchell (online at http://www.lornajane.net)
Re: Guess the magic number: Using constants effectively in PHP [message #2077 is a reply to message #1281 ] Wed, 02 July 2008 16:31 Go to previous messageGo to next message
dcousineau  is currently offline dcousineau
Messages: 6
Registered: July 2008
Location: College Station
Shiny and New
You are actually better off throwing the example in a switch statement. Since you are testing the same variable, it ends up being easier to read (and lets the compiler do some optimizations):

<?php
define('MEANING_OF_LIFE', 42);
define('GROSS', 144);
define('KILOBYTE', 1024);

switch( $variable )
{
	case MEANING_OF_LIFE:
		echo 'I know the meaning of life!';
		break;
	case GROSS:
		echo 'Thats gross!';
		break;
	case KILOBYTE:
		echo 'I am a kilobyte';
		break;
	default:
		//default?
}
?>


Constants work real well with switch statements, especially when doing things like state machine parsers and any logic blocks dealing with testing a parameter or variable against constants.


Daniel Cousineau
Project Manager at Net Perspective, LLC.
My Blog of Pure Awesome
Re: Guess the magic number: Using constants effectively in PHP [message #2876 is a reply to message #2077 ] Sat, 31 October 2009 18:02 Go to previous message
JaneSM  is currently offline JaneSM
Messages: 2
Registered: October 2009
Shiny and New
This is a good thread to start with in this forum.


Jane Smith
Previous Topic:Exceptions: errors on steroids
Next Topic:according to me
Goto Forum:
  


Current Time: Fri Jul 30 12:10:32 EDT 2010

Total time taken to generate the page: 0.01084 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.0.
Copyright ©2001-2006 FUD Forum Bulletin Board Software