A constant is an identifier (name) for a simple value. As the name suggests, the value cannot be changed during the execution of the script. Constants are automatically global across the entire script.
Unlike variables, constants do not have a dollar sign ($). There are two
ways to create a constant: using the define() function or the
const keyword.
The define() function takes two main parameters: the name of the constant
and its value.
<?php
define("GREETING", "Welcome to RedoHub!");
echo GREETING;
?>
The const keyword is often used within classes, but it can also be used in
the global scope. It is simpler but has some limitations compared to define().
<?php
const SITE_NAME = "RedoHub";
echo SITE_NAME;
?>
In PHP 7+, you can also create constant arrays using the define() function.
<?php
define("CARS", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo CARS[0];
?>
Unlike variables, constants are automatically global. They can be
accessed from anywhere in the script, including inside functions, without using the
global keyword.
<?php
define("DATABASE", "users_db");
function myTest() {
echo DATABASE; // Accessible here!
}
myTest();
?>
PHP provides many "Magic Constants" that change depending on where they are used. They all start and end with double underscores.
| Constant | Description |
|---|---|
__LINE__ |
The current line number in the file. |
__FILE__ |
The full path and filename of the file. |
__DIR__ |
The directory of the file. |
__FUNCTION__ |
The name of the current function. |
$).