login

PHP Constants

Constant like its name implies, its value cannot be changed during execution of program. In PHP you use define() function to define a constant. The define() function takes the name of constant as the first parameter and the constant's value as the second parameter. Unlike a variable, PHP constants do not start with $ sign.

If the name of constant is stored in a variable, you need to use a built-in function constant() to return constant's value.

This is an example of using PHP constant:

<?php
  define("GREETING", "PHP Constants ");
  echo GREETING; // outputs "PHP Constants"

  $constant_name = "GREETING";
  echo constant($constant_name);
?>

It’s best practice to capitalize a variable name for constants. Once constant is defined, it can be accessed globally. You cannot redefine or undefine  a constant. PHP constants often use to store values that do not change throughout program such as configuration.

PHP predefined constants

PHP provides several helpful predefined constants which usually start and end with two underscores. For example __FILE__ constant returns the name of PHP file that's being executed and __LINE__ returns line number of that file.

 

<?php
   echo "Executing line " . __LINE__ . 
        " of PHP file" . __FILE__ . ".";
?>