Constantly use constants in PHP

I’m going to talk to you about a few ways to use PHP’s constants to save yourself a lot of time and hassle.

PHP has this cool thing called a “CONSTANT” that basically lets you define a string to represent a value that is available everywhere. it basically doesn’t have a variable scope.

Note: a constant cannot be an array. It can be anything else, just not an array.

Syntax
define(’CONSTANT_NAME’, ‘VALUE’);

In a nutshell, a constant can be useful for anything from the maximum amount of failed logins you allow before prompting for CAPTCHA or simply banning their IP temporarily.

For example, Instead of having to type crainbandy.com/link or if you’re linking a stylesheet like http://www.crainbandy.com/style.css, or anything you can just use a constant to represent it.

The good thing about using constants inside your scripts is that instead of changing your entire script to adjust URL changes or any type of change, you can just change the constant.

Compare the two pieces of code below:

<?php
include(’/crainbandy/header.template’);
include(’/crainbandy/navigation.template’);
include(’/crainbandy/body.template’);
include(’/crainbandy/secondary.template’);
include(’/crainbandy/footer.template’);
?>

This is a horrible way to build pages (I just wanted to give an example of how to help streamline your scripts using constants)

<?php
define(’ROOT_DIR’, ‘/crainbandy/’);
include(ROOT_DIR . ‘header.template’);
include(ROOT_DIR . ‘navigation.template’); include(ROOT_DIR . ‘body.template’);
include(ROOT_DIR . ’secondary.template’);
include(ROOT_DIR . ‘footer.template’);
?>

Comparing the two blocks of code above it seems like you actually waste more time defining a constant as opposed to just writing out the directory. Well you don’t.
What if your root directory changed from /crainbandy/ to /html/ ? you’d have to change every line. Sure this would take about 2 seconds on the top and about half a second on the bottom block of code but when you have a 10 file web site using the same directories and URLs repeatedly. It is a life saver.
So, use constants. You’ll thank me later.

bryan

Related reading

2 Responses to “Constantly use constants in PHP”

  1. Manisekaran  on August 18th, 2006

    Good Development work for PHP

    http://www.eworldtechnologies.com

    Best Regards
    Manisekaran


Leave a Reply