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

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:
{code type=php}define(‘MYSQL_DB_NAME’, ‘cheeseypoofs’);{/code}

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

{code type=php}# Echo it

{code type=php}# Use it in a function
mysql_select_db(MYSQL_DB_NAME, $db);{/code}

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

Leave a Comment

Previous post:

Next post: