5. Constants
Constants are like variables, but once a constant is defined it cannot be changed or undefined.
1) PHP constants
A constant is an identifier (name) for a single value. This value cannot be changed in script.
Valid constant names start with a character or an underscore (there is no $ sign before the constant name).
Unlike variables, constants are automatically global throughout the script.
To set constants, use the define() function - it takes three arguments:
- The first parameter defines the name of the constant
- The second parameter defines the value of the constant
- An optional third parameter specifies whether the constant name is case-insensitive. The default is false.
The following example creates a case-sensitive constant with the value "Welcome to W3School.com.cn!":
Example:
<?php
define("GREETING", "Welcome to W3School.com.cn!");
echo GREETING;
?>
The following example creates a case-insensitive constant with the value "Welcome to W3School.com.cn!":
Example:
<?php
define("GREETING", "Welcome to W3School.com.cn!", true);
echo greeting;
?>
constants are global
Constants are automatically global and available throughout the entire script.
The following example uses a constant inside a function even though it is defined outside the function:
Example:
<?php
define("GREETING", "Welcome to W3School.com.cn!");
function myTest() {
echo GREETING;
}
myTest();
?>