In PHP, constant is an identifier which holds a constant value. The value of constant cannot be changed while executing the script.
Constants are declared by using define() function.
define (name, value, case-insensitive)
Name and value are mandatory parameters. Whereas, case-insensitive is an optional parameter. Its default value is false.
<?php
// Valid constant names
define("DATABASE", "Wordpress");
define("DATABASE2", "Magento");
define("DATABASE_SYMPHONY", "Symphony");
// Invalid constant name
define("3DATABASE", "Symphony");
// Valid constant name, but do not suggest as PHP my use same name as magical constant in future,
// which may break your script.
define("__DATABASE__", "Joomla");
echo DATABASE . "<br>";
echo DATABASE2 . "<br>";
echo 3DATABASE . "<br>"; // This will generate an error
echo __DATABASE__ . "<br>";
?>
Alternatively, constant variable can be defined using const keyword.
<?php
const KH_NAME = "John";
echo "My name is " . KH_NAME;
?>
It is used to retrieve the value of constant. It is helpful when you know the name of constant and want to retrieve its value.
<?php
define("KH_NAME", "My name is John");
echo constant("KH_NAME");
?>
It will return the array of constants name and their values. It include the default constants as well as user defined constants.
<?php
define("KH_DATABASE", "Wordpress");
define("KH_USER", "John");
const KH_PASSWORD = "password";
echo "<pre>";
print_r(get_defined_constants());
echo "</pre>";
?>