In PHP, constant is an identifier or a name for a fixed value in a program. A constant value cannot modify during the implementation of the script. Constant are same like variables except that one they are defined, they cannot be undefined or modified (except the magic constants).
Constants are very helpful for saving the data that don't vary while the script is executing.
Common examples of such data comprise configuration settings such as database passwords and username, company name, website's URL, etc.
PHP constants can be categorized in two ways:
- Using define() function
- Using const keyword
PHP constants follow the same rules as PHP variable rules. For instance, it can be initiated with a letter or underscore only. Usually, PHP constants should be expressed in the uppercase letters.
Let's see the syntax of define() function in PHP.
define(name, value, case-insensitive)
name: shows the constant name
value: show the constant value
case-insensitive: Its default value is false. It signifies that it is case sensitive by default.
Let's see the example to define the PHP constant using define().
<?php define("MESSAGE","Hello PHP"); echo MESSAGE; ?>
Result: Hello PHP
<?php define("MESSAGE","Hello PHP",true); //not case sensitive echo MESSAGE; echo message; ?>
Result: Hello PHP Hello PHP
<?php define("MESSAGE","Hello PHP",false); //case sensitive echo MESSAGE; echo message; ?>
Result: Hello PHP
Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
PHP constant: const keyword
The const keyword shows constants at running time. It is a kind of language constructs not any function.
It is a bit quicker than define().
It is always used as case sensitive.
<?php const MESSAGE="Hye const by CodingTag PHP"; echo MESSAGE; ?>
Result: Hye const by CodingTag PHP