PHP 5 Constants
Once a constant value is defined, it cannot be changed anywhere else in the script.
PHP Constants
A constant is an identifier for a simple value. The value cannot be changed during the script.
A constant consists of English letters, underscores, and numbers, but the number cannot be the first character. (The constant name does not require a $ modifier).
Note: Constants can be used throughout the script.
Setting PHP Constants
To set a constant, use the define() function, which has the following syntax:
bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )
The function has three parameters:
name: Required parameter, the constant name, i.e., the identifier.
value: Required parameter, the value of the constant.
case_insensitive: Optional parameter, if set to TRUE, the constant is case-insensitive. By default, it is case-sensitive.
The following example creates a case-sensitive constant with the value "Welcome to tutorialpro.org":
Example
<?php
// Case-sensitive constant name
define("GREETING", "Welcome to tutorialpro.org");
echo GREETING; // Outputs "Welcome to tutorialpro.org"
echo '<br>';
echo greeting; // Outputs "greeting" with a warning, indicating the constant is undefined
?>
The following example creates a case-insensitive constant with the value "Welcome to tutorialpro.org":
Example
<?php
// Case-insensitive constant name
define("GREETING", "Welcome to tutorialpro.org", true);
echo greeting; // Outputs "Welcome to tutorialpro.org"
?>
Constants are Global
Constants, once defined, are global variables by default and can be used anywhere in the script.
The following example demonstrates using a constant inside a function, even if the constant is defined outside the function.
Example
<?php
define("GREETING", "Welcome to tutorialpro.org");
function myTest() {
echo GREETING;
}
myTest(); // Outputs "Welcome to tutorialpro.org"
?>