Current Location: Home> Latest Articles> PHP Constants Tutorial: How to Create and Use Constants in PHP

PHP Constants Tutorial: How to Create and Use Constants in PHP

M66 2025-07-12

PHP Constants Tutorial: How to Create and Use Constants in PHP

In PHP, constants are used to store values that cannot be modified. You can define constants using the define() function, specifying the constant's name and value, and optionally choosing whether it is case-sensitive or not.

How to Define Constants in PHP

Defining a constant is very simple; you just need to use the define() function.

Syntax:

define(name, value, [case-insensitive]);

Parameter Explanation:

  • name: The name of the constant, which must be a valid PHP identifier.
  • value: The value of the constant, which can be any data type.
  • case-insensitive (optional): If set to true, the constant name will be case-insensitive.

Examples:

define('PI', 3.14159265); // Define a float constant
define('TAX_RATE', 0.08); // Define a numeric constant
define('COMPANY_NAME', 'Acme Corp.'); // Define a string constant

Accessing Constants:

You can directly access a defined constant by its name:

echo PI; // Output 3.14159265
echo TAX_RATE; // Output 0.08
echo COMPANY_NAME; // Output Acme Corp.

Important Notes:

  • The constant name must start with a letter or an underscore and cannot contain special characters.
  • Once defined, the value of a constant cannot be modified or redefined.
  • Constants can be accessed anywhere in the script.
  • Constant names are typically written in uppercase letters to signify that their values cannot be changed.

By mastering PHP constants, you can handle values that do not need to change, improving the maintainability and readability of your code.