As its name suggests, these are constants that can be used in PHP, defining them in PHP instead of using data directly, which does not need to change during the run time. Constants, once defined, cannot be altered or can never be undefined. So once it is defined, the constant value will be available during the entire execution of that script or file.
PHP constants
- PHP constants can be defined using define() function
- PHP constants can be defined using const keyword
- It is case-insensitive
- Constants are global by default
Lets have a look at PHP constants in detail.
PHP constants using define() function
PHP constants can be defined using define() function. This function accepts two parameters. Name and value.
Prior to PHP 8.0.0, constants defined using the define() function may be case-insensitive by passing an extra parameter. Now this feature is completely removed.
define(name, value)
name : Specifies the name of the constant
value : Value assigned to that constant
Example
<?php
define("SUBJECT","Hello World!");
echo SUBJECT;
?>
The above PHP script will give a Hello World!
as output.
PHP constants using const keyword
Constants can also be defined using const keyword.
<?php
const SUBJECT="Hello world from const";
echo SUBJECT;
?>
The above PHP script will give a Hello world from const
as output.