Current Location: Home> Latest Articles> PHP Constants Explained: Built-in and User-defined Constants

PHP Constants Explained: Built-in and User-defined Constants

M66 2025-09-29

Overview of PHP Constants

PHP offers built-in constants and user-defined constants, declared using the PHP_ prefix and the const keyword, respectively. Built-in constants allow access to system-specific information such as the PHP version or operating system, while user-defined constants are created by developers, follow strict naming rules, and cannot be modified once defined.

Built-in Constants

PHP provides various built-in constants that help retrieve system information or specific functionalities in code. Common built-in constants include:

  • PHP_VERSION: The current PHP version
  • PHP_OS: The current operating system
  • PHP_EOL: End-of-line character
  • PHP_INT_MAX: Maximum integer value
  • PHP_INT_MIN: Minimum integer value

User-defined Constants

In addition to built-in constants, developers can define their own constants. User-defined constants are declared using the const keyword. Constant names must start with a letter or underscore and can only contain letters, numbers, or underscores.

Naming Conventions

It is recommended to use uppercase letters and underscores when naming user-defined constants. This helps distinguish them from variables. For example:

<span class="fun">const MY_CONSTANT = 'VALUE';</span>

Accessing Constants

Constants can be accessed directly by their name. Unlike variables, constants cannot be reassigned once defined.

Example

Here is an example demonstrating the use of both built-in and user-defined constants:

<?php
echo PHP_VERSION . PHP_EOL;

const MY_CONSTANT = 'Hello, world!';

echo MY_CONSTANT;
?>

The above content provides a detailed explanation of PHP constants, including types, naming conventions, and usage methods, helping developers better understand and apply PHP constants in their projects.