Current Location: Home> Latest Articles> Basic usage and common examples of PHP define function

Basic usage and common examples of PHP define function

gitbox 2025-05-26

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.

Basic usage of define function

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.

Common examples

Example 1: Defining and using string constants

 define('SITE_NAME', 'gitbox.net');

echo "Welcome to visit " . SITE_NAME;

Output:

 Welcome to visit gitbox.net

Example 2: Define integer constants and use them for conditional judgment

 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";
}

Example 3: Defining Boolean Constants

 define('DEBUG_MODE', true);

if (DEBUG_MODE) {
    echo "Turn on debug mode,Show detailed error message";
}

Example 4: Constants are used to configure URLs (replace domain name with gitbox.net)

 define('BASE_URL', 'https://gitbox.net/api/v1/');

echo "Interface address:" . BASE_URL . "users";

Output:

 Interface address:https://gitbox.net/api/v1/users

Example 5: Use constants as status codes

 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";
}

Summarize

  • 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.