PHP constants are used to store values that cannot be changed during the script execution. Constants are globally accessible throughout the script, and they do not require a dollar sign ($) prefix like variables.
define()
The define()
function is used to define a constant in PHP. Once defined, the constant's value cannot be changed.
<?php
define("PI", 3.14159); // Defining a constant
echo "The value of PI is: " . PI . "<br>";
?>
The value of PI is: 3.14159
By default, constants in PHP are case-sensitive. You can make them case-insensitive by setting the third parameter of define()
to true
.
<?php
define("GREETINGS", "Hello, AIT!", true); // Case-insensitive constant
echo GREETINGS . "<br>"; // Works with any case
echo greetings . "<br>"; // Also works with lowercase
?>
Hello, AIT!
Hello, AIT!
PHP provides several built-in constants, such as PHP_VERSION
, PHP_OS
, and others.
<?php
echo "PHP Version: " . PHP_VERSION . "<br>";
echo "Operating System: " . PHP_OS . "<br>";
?>
PHP Version: 8.0.0
Operating System: Linux
Constants are ideal for values that should remain unchanged throughout the execution of the program, such as configuration values or mathematical constants.