A constant is a name used to store a fixed value that does not change during the execution of a PHP script. Unlike variables, constants do not start with a $ symbol and cannot be modified once they are defined.
- Constants are immutable (their value cannot be changed).
- They are global by default and can be accessed from anywhere in the script.
- Constants do not start with a $ symbol.
- By convention, constant names are written in UPPERCASE.
Creating a Constant in PHP
There are two ways to create constants in PHP:
1. Using define() Function
The define() function in PHP is used to create a constant, as shown below:
Syntax:
define( name, value);The parameters are as follows:
- name: The name of the constant.
- value: The value to be stored in the constant.
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;
?>
2. Using the 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;
?>
define() vs. const
| define() | const |
|---|---|
| A function used to define constants. | A keyword used to declare constants. |
| Defines constants at runtime. | Defines constants at compile time. |
| Case-insensitive option was supported in older PHP versions but is no longer supported in PHP 8.0 and later. | Constant names are case-sensitive by default. |
| Suitable for dynamically named constants. | Preferred for declaring constants in modern PHP code. |
Constants are Global
By default, constants are global and can be used throughout the script, accessible inside and outside of any function.
Example:
<?php
define("WELCOME", "GeeksforGeeks");
function testGlobal() {
echo WELCOME;
}
echo WELCOME . "\n";
testGlobal();
?>
Predefined Constants in PHP
PHP provides many built-in constants, such as:
- PHP_VERSION: Current PHP version
- PHP_OS: Operating system name
- PHP_INT_MAX: Maximum integer value
- PHP_FLOAT_MAX: Maximum float value
Constants vs. Variables
Both are used to store values in PHP. Constants hold fixed values that never change, whereas variables can be updated as the script runs. Below is the difference between them:
Constant | Variable |
|---|---|
Used to store values that do not change during script execution. | Used to store values that can change while the script runs. |
Defined once and cannot be redefined. | Can be updated or reassigned multiple times. |
Do not start with a $ symbol. | Always start with a $ symbol. |
Value stays the same everywhere in the program. | Value can be different in different parts of the program. |