Storing Simple Values and Parameters – define() your PHP constants

by Carey on November 10, 2010

Post image for Storing Simple Values and Parameters – define() your PHP constants
  • Share
  • CevherShare
  • Share

In most applications there is a need for set values that do not change during the execution of a script. Examples of these values are:

  • Database Settings (username, password etc.)
  • Database Table Names
  • Directory Paths
  • Website URLs

A bad way to handle these values is to “hard code” them. This is the process of inserting the values in your code as and when you need them. This will make the values hard to change as the same value will be repeated throughout your application.

A good way to handle these values is to set them as constants and store them in a seperate file (or files) and include them in your main scripts. That way a change to these values is easy and you are seperating your configuration values from your logic.

A constant is defined as a simple value that cannot change during execution and is a common feature of most programming languages.
When using constants avoid setting them as normal variables as this means it is possible to change or overwrite them. Instead use the php function define() to properly set your constants, as follows:

define('MYSQL_DB_NAME', 'cheeseypoofs');

This sets the value ‘localhost’ to the constant MYSQL_DB_NAME. It can be used as follows:

# Echo it
echo MYSQL_DB_NAME;
# Use it in a function
mysql_select_db(MYSQL_DB_NAME, $db);

Using constants will help you to write clean and maintainable code.

Leave a Comment

Previous post:

Next post: