PHP Constants
Constants in PHP are identifiers or names that can be assigned any fixed values and cannot change during the execution of a program. They remain constant throughout the program and cannot be changed during the execution. Once a constant is defined, it cannot be undefined or redefined.
By convension, constant identifiers are always written in upper case. By default, a constant is always case-sensitive. 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.
Table of Content
Creating a Constant using define() Function
The define() function in PHP is used to create a constant as shown below:
Syntax
define( 'CONSTANT_NAME', value, case_insensitive )
The parameters are as follows:
- name: The name of the constant.
- value: The value to be stored in the constant.
- case_insensitive: Defines whether a constant is case insensitive. By default this value is False, i.e., case sensitive.
Example: Creating constants using define() function.
<?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
Creating a Constant using const Keyword
The const keyword is another way to define constants but is typically used inside classes and functions. The key difference from define() is that constants defined using const cannot be case-insensitive.
Syntax
const CONSTANT_NAME = value;Example:
<?php
const SITE_NAME = 'GeeksforGeeks';
echo SITE_NAME;
?>
Output
GeeksforGeeks
Constants are Global
By default, constants are global, and can be used throughout the script, accessible inside and outside of any function.
Example: Constants are global and accessible inside and outside of the block.
<?php
define("WELCOME", "GeeksforGeeks");
function testGlobal() {
echo WELCOME;
}
echo WELCOME . "\n";
testGlobal();
?>
Output
GeeksforGeeks GeeksforGeeks
Difference Between Constants and Variables
Although both constants and variables are used to store values, they differ in several ways:
| Feature | Constants | Variables |
|---|---|---|
| Syntax | No dollar sign ($) | Starts with a dollar sign ($) |
| Value | Immutable | Mutable |
| Case Sensitivity | Case-sensitive (default) | Case-sensitive |
| Global Scope | Always global | Scope can vary (local or global) |
| Declaration Methods | define() or const | Use of $ symbol |


