PHP - Constants

  »   PHP  »   PHP Tutorial - Constants

A constant is a type of variable that cannot be changed. A constant cannot be undefined and once his value has been set, it can not change his value along the script.

Constants are usually found in configuration files containing information such as database user and password, database name, site URL and other useful data.

This is how you define a constant in PHP:

PHP<?php

	// site name
	define('SITE_NAME', 'my cool site name', flase);

	// database conection
	define('DB_INFO', array(
		'host'=> 'localhost', 
		'usr' => 'my_user',
		'pass'=> 'my_database_pass',
		'db'  => 'my_database')
	);


	echo "Wellcome to " SITE_NAME;
	echo "<br />"
	var_dump(DB_INFO);
?>

Let's take a closer look at the examples above. We used the define() function to create the constant and with the following params:

  • name - the defined name for our constant
  • value - the defined value for our constant
  • case-sensitive - this is an optional param and it is true by default. This means that our constant is case sensitive. Set it to false if you need it

Naming constants

Just like a normal variable a valid constant name starts with a letter or underscore. On the other hand, a PHP constant doesn't need the "$" sign before the constant name.

Although it is not a must, there is a convention that constant names to be written in uppercase letters. This makes it easy for the identification and distinguishes them from other variables when reviewing coding documents.

Constants scope

Constants are automatically defined as globals and can be directly used anywhere around the script without further action.

PHP<?php
	// database connection
	define('DB_INFO', array(
		'host'=> 'localhost', 
		'usr' => 'my_user',
		'pass'=> 'my_database_pass',
		'db'  => 'my_database')
	);

	// simple function too print data
	function nice_printing(){
		echo "<pre>";
		print_r(DB_INFO);
		echo "</pre>"
	}

	// function execution
	nice_printing();
?>

Check if a constant has been defined

Although we have not wet talked about the if/else tag yet, this is a good place to mention that constants have a specific function to check if they are defined.

For variables we will use isset() while for constants we will use defined(). Here is an example using it on a constant:

PHP<?php
	define('DEBUG_LEVEL', 3);

	if(defined(DEBUG)) {
		// do something if debug is defined
	}
?>