Open In App

PHP | Constants

Constants are either identifiers or simple names that can be assigned any fixed values. They are similar to a variable except that they can never be changed. They remain constant throughout the program and cannot be altered during execution. Once a constant is defined, it cannot be undefined or redefined. Constant identifiers should be written in upper case following the convention. By default, a constant is always case-sensitive, unless mentioned. A constant name must never start with a number. It always starts with a letter or underscores, followed by letter, numbers or underscore. It should not contain any special characters except underscore, as mentioned.

Creating a PHP Constant



The define() function in PHP is used to create a constant as shown below:
Syntax:

define(name, value, case_insensitive)

The parameters are as follows:



Example:




<?php
  
// This creates a case-sensitive constant
define("WELCOME", "GeeksforGeeks");
echo WELCOME, "\n";
  
// This creates a case-insensitive constant
define("HELLO", "GeeksforGeeks", true);
echo hello;
  
?>

Output:

GeeksforGeeks
GeeksforGeeks

constant() function

Instead of using the echo statement ,there is an another way to print constants using the constant() function.

Syntax

constant(name)

Example:




<?php
  
   define("WELCOME", "GeeksforGeeks!!!");
     
   echo WELCOME, "\n";
  
   echo constant("WELCOME"); 
   // same as previous
  
?>

Output:

GeeksforGeeks!!!
GeeksforGeeks!!!

Constants are Global: By default, constants are automatically global, and can be used throughout the script, accessible inside and outside of any function.
Example:




<?php
  
define("WELCOME", "GeeksforGeeks");
  
function testGlobal() {
    echo WELCOME;
}
   
testGlobal();
  
?>

GeeksforGeeks

Constants vs Variables


Article Tags :