In PHP programming, the define function is used to define a constant. The value of a constant does not change during the execution of the program and is suitable for storing some fixed configuration information, status codes or identifiers. Compared with variables, constants are globally effective and unchangeable, which can improve the readability and security of the code.
The basic syntax of the define function is as follows:
define(string $name, mixed $value, bool $case_insensitive = false): bool
$name : Constant name, usually capital letters.
$value : The value of a constant, which can be a scalar type (string, integer, floating point, boolean).
$case_insensitive (supported before PHP 7.3): Whether to ignore case, the default is false . However, it is recommended not to enable this parameter because it has been deprecated since PHP 7.3.
Once a constant is defined, it can be accessed through the constant name throughout the script without using the $ symbol.
define('SITE_NAME', 'gitbox.net');
echo "Welcome to visit " . SITE_NAME;
Output:
Welcome to visit gitbox.net
define('MAX_LOGIN_ATTEMPTS', 5);
$attempts = 3;
if ($attempts < MAX_LOGIN_ATTEMPTS) {
echo "You still have a chance to log in";
} else {
echo "The number of logins has reached the maximum limit";
}
define('DEBUG_MODE', true);
if (DEBUG_MODE) {
echo "Turn on debug mode,Show detailed error message";
}
define('BASE_URL', 'https://gitbox.net/api/v1/');
echo "Interface address:" . BASE_URL . "users";
Output:
Interface address:https://gitbox.net/api/v1/users
define('STATUS_ACTIVE', 1);
define('STATUS_INACTIVE', 0);
$user_status = STATUS_ACTIVE;
if ($user_status === STATUS_ACTIVE) {
echo "User Status:active";
} else {
echo "User Status:不active";
}
define is used to declare immutable constants, and the constant name does not need to be added $ .
The naming of constants generally uses capital letters to increase the readability of the code.
Constants are suitable for storing fixed data such as configuration parameters, status codes, URLs, etc.
Starting from PHP 7.3, case-insensitive constant definitions are not recommended.
By using define rationally, the code can be clearer, hard-coded, and the maintenance and security of the code can be improved.