A constant is a name or identifier 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 stay the same once they are defined.
- Constants are immutable (cannot be changed after definition).
- They are global by default and accessible from anywhere in the script.
- Constants do not start with a $ symbol.
- Constants are written in uppercase letters by convention.
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.
Now, let us understand with the help of the 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
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;Now, let us understand with the help of the example:
<?php
const SITE_NAME = 'GeeksforGeeks';
echo SITE_NAME;
?>
Output
GeeksforGeeks
define() vs const
define() | const |
|---|---|
Used to create constants using a function. | Used to create constants using a keyword. |
Works at runtime. | Works at compile time. |
Slightly older and more flexible. | Preferred in modern PHP code for structure and readability. |
Constants are Global
By default, constants are global and can be used throughout the script, accessible inside and outside of any function.
Now, let us understand with the help of the example:
<?php
define("WELCOME", "GeeksforGeeks");