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 Reply

Your email address will not be published.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,


If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the