Read Time:1 Minute, 21 Second
PHP – Constants Defined

- A constant is an identifier (name) for a simple value. That value cannot change during the execution of the PHP script. Constants are case-sensitive. By convention, constant identifiers are always uppercase.
- The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores,PHP constants should be defined in uppercase letters.
Note:
Prior to PHP 8.0.0, constants defined using the define() function may be case-insensitive.
PHP constants can be defined by 2 ways:
- Using define() function
- Using const keyword
PHP constant: define() function
Syntax:
define(name, value)
- name: It specifies the constant name.
- value: It specifies the constant value..
Let’s see the example to define PHP constant using define().
<?php
define("MESSAGE","HELLO CodeDixa");
echo MESSAGE;
?>
Output:
HELLO CodeDixa
PHP constant: const keyword
- PHP introduced a keyword const to create a constant.
- The const keyword defines constants at compile time.
- It is a language construct, not a function.
- The constant defined using const keyword are case-sensitive.
Example:
<?php
const MESSAGE="Hello const by CodeDixa PHP";
echo MESSAGE;
?>
Output:
Hello const by CodeDixa PHP
constant() function
There is another way to print the value of constants using constant() function instead of using the echo statement.
Syntax:
constant(name);
Example:
<?php
define("MSG","Welcome to CodeDixa");
echo MSG."<br>";
//or
echo constant("MSG");
//both are smiliar
?>
Output:
Welcome to CodeDixa
Welcome to CodeDixa
Average Rating