Using PHP Constants
Using PHP constants in scripts that I write is something I do quite often. I don't know about you, but I am almost obsessive about using them! They're SO easy to use, so useful and so simple - which is what I like about PHP anyway...
If you don't use them or rarely find the need to use PHP constants in your scripts, this article could change your mind.
How do I create (define) a PHP constant?
You create or 'define' a constant by using the define() function:
<?php
// define your site name, since it does NOT change
// anywhere within your script.
define( 'SITE_NAME', 'Learning Journal' );
// define the current year, possibly to use in your copyright
// statement or for 'date' calculations
define( 'THIS_YEAR', date('Y') );
// even use existing constants to create other constants!
// e.g. adding the trademark symbol to your site name...
define( 'SITE_NAME_T', SITE_NAME.'™' );
?>
Tips for using PHP constants in your scripts
There are too many useful uses for PHP constants to list them all here. However, besides the obvious ones already shown in the sample code above, I also use them for file system, paths and such...
<?php
// define the WWW root for my website. It's easier for me
// to type DOC_ROOT instead of $_SERVER['DOCUMENT_ROOT']!
define( 'DOC_ROOT', '/home/username/public_html' );
// define the include folder
define( 'INCLUDES', DOC_ROOT.'/../includes' );
// define the classes / library folder
define( 'CLASSES', DOC_ROOT.'/../classes' );
// define some 'escape sequence' characters
define( 'NL', "\n" );
define( 'TB', ' ' );
// ======================================
/* SAMPLE CODE SNIPPETS USING THE CONSTANTS
DEFINED ABOVE */
// echo a paragraph with our site name
echo '<p>The '.SITE_NAME.' by<br />'.NL
.TB.'J de Silva.</p>'.NL;
// including an include and class file
include_once( INCLUDES.'/functions.inc.php' );
include_once( CLASSES.'/cls_validate.inc.php' );
?>
Some important facts about PHP Constants
-
By far, the most important benefit of using constants is that the scope of a constant is global; you can even use it inside functions and classes!
Since they are constants, you cannot change the value of a constant midway in your scripts.
A constant is case sensitive by default; so SITE_NAME is not the same as site_name unless you used the third optional parameter when you defined the constant.
A constant cannot contain an array for example. Only the following data 'types':
<?php
// String
define( 'AUTHOR', 'J de Silva' );
// Integer
define( 'COLUMNS', 3 );
// Boolean
define( 'SHOW_MENU', FALSE );
// Float
define( 'DISCOUNT_50', 0.5 );
?>
