Constants In PHP

Loading

We are all familiar with variables. As the name suggests the value of the given variable tends to vary.


<?php
 $fruit 
'orange';
 print 
$foo;
 
$foo 'banana';
 print 
$foo;
?>

The above script illustrates the usage of variables. Variables in PHP are represented by a dollar sign followed by the name.

Just like variables, PHP offers constants. As the name suggests the value of the constant does not change throught the lifetime of the script.

How do you use constants?

Define a constant and use it to print or assign its value to a variable.


<?php
define
('MY_FRUIT''pineapple');
echo 
MY_FRUIT;
?>

In the above example, we define the constant MY_FRUIT and assign the value 'pineapple' to it. We print the value of the constant 'MY_FRUIT'. Notice, we don't use the '$' symbol to represent constants. Once the constant is defined its value cannot be changed.

The following examples shows incorrect usage of constants.


<?php
define
('MY_FRUIT''pineapple');
echo 
MY_FRUIT;
MY_FRUIT 'banana';
?>


PHP Parse error:  syntax error, unexpected '=' in ../constant/basic.php on line 4
?>

Why is the constant in upper case in the above examples?
In our above examples, The characters that represent the constants are known as identifiers. Constant identifiers are case sensitive. It is perfectly legal to use lower case letters in constant identifier. However, it is a convention to use only upper case letters in constant identifiers.

How do I determine whether a constant is already defined?
Use the built in function defined(). Here's a script to illustrate the usage of defined().


<?php
if (defined('MY_VEGETABLE')) {
  echo 
'The constant is already defined';
} else {
  echo 
"\n" 'The constant is not defined. We will now';
  
define('MY_VEGETABLE''carrot');
  echo 
"\n" ' The value of the constant MY_VEGETABLE is ' MY_VEGETABLE;
}

?>

Sometimes, you would want to store the name of the constant in a variable. You will also come across situation where you have to concatenate strings to represent a constant.

The following is incorrect syntax.


<?php
    define
('MY_VEGETABLE''carrot');
    echo 
MY_ 'VEGETABLE';
?>
PHP Notice:  Use of undefined constant MY_ - assumed 'MY_' in constant/defined.php on line 3
?>

In order to circumvent, you use the constant() function.


<?php
define
('HTTP_PORT''80');
define('FTP_PORT''21');

$protocol 'HTTP';
echo 
"\n" " The port number for protocol $protocol is " constant($protocol '_PORT');

$protocol 'FTP';
echo 
"\n" " The port number for protocol $protocol " constant($protocol '_PORT');
?>

Output:

The port number for protocol HTTP is 80
The port number for protocol FTP 21
?>

The function constant() provides flexibility to use constants in PHP scripts.

Predefined constants

PHP offer numerous predefined constants. PHP_VERSION and PHP_OS are two examples of predefined constants. The function get_defined_constants() returns an array of defined constants with its values.

To inspect the list of constants use this script:


<?php
$constants 
get_defined_constants();
foreach (
$constants as $key=>$value){
    echo 
"\n" "The constant is " $key " and its value is " $value;
}

?>

Magic constants

There are seven magic constants provided by PHP. The value of magic constants depend on the context unlike regular constants. Hence the title, magic. Visit the section on predefined constants at PHP.net for a tabular list of magic constants and their purposes.

Here is a script to demonstrate the usage of magic constants.


<?php
/**
 * Script to demonstrate magic constants in php
 */

echo "\n" "We are at line " __LINE__;
echo 
"\n" "The full path and filename of the file is " __FILE__;

function 
myFunction(){
    echo 
"\n" "The function name is " __FUNCTION__;
}

myFunction();

class 
myClass
{
    public function 
__construct()
    {
        echo 
"\n" "The class name is " __CLASS__;
        echo 
"\n" "The method name is "__METHOD__;
    }
}

$object = new myClass();
echo 
"\n";
?>
Sample output of the script:

We are at line 6
The full path and filename of the file is /home/sudheer/workspace/php/cli/constant/magic.php
The function name is myFunction
The class name is myClass
The method name is myClass::__construct

?>

Class constants

Classes can have their own constants. You define the class constant using the syntax
const MY_CONSTANT_NAME = 'class constant value';

You can access the class constant using the :: operator.
classname::constantname

A script to demonstrate the class constant follows:


<?php
define
('MY_FRUIT''banana');

class 
myClass
{
    const 
MY_FRUIT 'orange';
}
echo 
"\n" MY_FRUIT;
echo 
"\n" myClass::MY_FRUIT;
?>
Output: 
banana
orange
?>

Notice the usage of the same constant identifier MY_FRUIT.

Where to use?

We have now learned a great deal about constants in PHP. Where do you practically use constants?

Use constants when you would like to access information globally. Typical usage of constants are found in applications defining constants of the application path. Some people also use constants to store database parameters like database name, database username and password. Class constants are often used to store error messages or status messages.

Tell us how and where do you use constants.

About the author

Sudheer is an entrepreneur and software developer. Get more from Sudheer on Twitter.


Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>. The supported tag styles are: <foo>, [foo].

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.