PHP Constants


A constant is name or identifier for a fixed value. Constants are like variables except that once they are defined they cannot be changed or undefined. A constant value can not change during the execution of the script. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

By default a constant is a case sensitive. Conventionally, PHP constant should be defined in uppercase letters. Constants are automatically global and can be used across the entire script.

In PHP there are two ways to define a constant :

1. Using define() function
2. Using const keyword

1. Using define() function :

With define() function we can create a constant variable in php. The syntax of define function is :
 define(name, value, case-insensitive);
Where name specifies the name of the constant, value specifies the value of the constant, case-insensitive specifies weather the constant should be case-insensitive. Default is false, means it is case-sensitive by default.

Example :
<?php
  define("NUM", "1200");
  echo NUM;
  echo "<br/>";

  define("MSG", "Hello world");
  echo MSG;
?>
Output :

1200
Hello world

As we can in the above example to access the constant variable defined with define() function, we do not need to use the $ (dollar) sign in front of the variable name. Now lets see another example with enabled case-insensitivity.
<?php
  define("MSG", "Hello world", true);
  echo msg;
?>
Output :

Hello world


2. Using const keyword :

In PHP we can also define the constant by using the const keyword. The syntax would be :
 const variable_name = value;
The const is a language construct not a function. It is a bit faster then define() function and always case-sensitive.
<?php
  const NUM = 1200;
  echo NUM;
  echo "<br/>";

  const str = "Hello world, This is test.";
  echo str;
?>
Output :

1200
Hello world, This is test.


Next Topic :