In PHP, a constant is a name or an identifier for a simple value.
Unlike variables, constants are immutable, meaning their values cannot be changed once they are defined.
Constants are used to define values that should remain the same throughout the execution of the script, such as configuration settings or environment-specific values.
This tutorial will cover:
Let’s explore each topic with examples and explanations.
1. Defining Constants Using define()
The most common way to define a constant in PHP is using the define() function. Once a constant is defined, its value cannot be changed, and it can be accessed anywhere in the script.
Syntax:
define("CONSTANT_NAME", value, case_insensitive);
- CONSTANT_NAME: The name of the constant (by convention, constant names are usually uppercase).
- value: The value of the constant.
- case_insensitive (optional): Set to true if you want the constant to be case-insensitive (deprecated as of PHP 8.0).
Example (Defining a Simple Constant):
<?php // Define a constant define("SITE_NAME", "My Website"); // Access the constant echo SITE_NAME; // Outputs: My Website ?>
- In this example, the constant SITE_NAME is defined with the value “My Website”. Once defined, its value can be accessed using the constant name without the $ symbol.
2. Defining Constants Using const (PHP 5.3+)
Another way to define constants is using the const keyword. Unlike define(), constants declared with const are defined at compile-time and cannot be used conditionally (i.e., inside loops or conditionals).
Syntax:
const CONSTANT_NAME = value;
Example (Defining a Constant with const):
<?php // Define constants using const const SITE_URL = "https://www.mywebsite.com"; const MAX_LOGIN_ATTEMPTS = 5; echo SITE_URL; // Outputs: https://www.mywebsite.com echo MAX_LOGIN_ATTEMPTS; // Outputs: 5 ?>
- In this example, the const keyword is used to define the SITE_URL and MAX_LOGIN_ATTEMPTS constants. These are accessed directly without the $ symbol.
3. Case-Sensitivity of Constants
In PHP, constants defined using the const keyword are always case-sensitive. However, constants defined using define() can be made case-insensitive by setting the third argument to true (deprecated as of PHP 8.0).
Example (Case-Sensitivity with define()):
<?php // Define a case-sensitive constant define("USERNAME", "admin"); // Try to access it in different cases echo USERNAME; // Outputs: admin echo username; // Outputs: Warning: Use of undefined constant 'username' ?>
- Constants are case-sensitive by default, so trying to access username results in an error.
Example (Deprecated Case-Insensitive Constants):
<?php // Define a case-insensitive constant (Deprecated in PHP 8.0) define("PASSWORD", "secret123", true); echo PASSWORD; // Outputs: secret123 echo password; // Outputs: secret123 (because of case insensitivity) ?>
- Case-insensitive constants were allowed before PHP 8.0 but are now deprecated. It is best practice to always use case-sensitive constants.
4. Predefined PHP Constants
PHP comes with several predefined constants that provide useful information about the environment, such as version information, directory paths, and more. Some of the most common predefined constants are:
- PHP_VERSION: The current version of PHP.
- PHP_OS: The operating system PHP is running on.
- PHP_EOL: The end-of-line character used by the current operating system.
Example (Using Predefined Constants):
<?php // Display PHP version echo "PHP Version: " . PHP_VERSION . "\n"; // Outputs: PHP Version: x.x.x // Display the operating system echo "Operating System: " . PHP_OS . "\n"; // Outputs: Operating System: Linux/Windows/... ?>
- These constants are automatically defined by PHP and can be accessed without needing to define them.
5. Magic Constants
PHP provides a set of magic constants that change depending on their context (i.e., where they are used). These constants are predefined and start with double underscores (__).
Some common magic constants are:
- __FILE__: The full path and filename of the current file.
- __DIR__: The directory of the current file.
- __LINE__: The current line number in the file.
- __FUNCTION__: The name of the current function.
- __CLASS__: The name of the current class.
Example (Using Magic Constants):
<?php echo "This file is: " . __FILE__ . "\n"; // Outputs the file path echo "This directory is: " . __DIR__ . "\n"; // Outputs the directory path echo "This is line number: " . __LINE__ . "\n"; // Outputs the current line number ?>
- Magic constants are especially useful for debugging and getting file and directory information dynamically.
6. Constant Arrays (PHP 5.6+)
Starting with PHP 5.6, it is possible to define constant arrays. This allows you to store multiple constant values in an array structure.
Example (Defining a Constant Array):
<?php // Define an array constant define("FRUITS", ["Apple", "Banana", "Cherry"]); // Access elements of the array constant echo FRUITS[0]; // Outputs: Apple echo FRUITS[1]; // Outputs: Banana ?>
- In this example, the FRUITS constant is an array, and its elements can be accessed using standard array syntax.
7. Checking if a Constant Exists (defined())
You can check if a constant is defined using the defined() function. This is useful for ensuring that a constant has been set before attempting to use it.
Syntax:
defined("CONSTANT_NAME");
Example (Using defined()):
<?php // Check if a constant is defined if (defined("SITE_NAME")) { echo "Constant SITE_NAME is defined."; } else { echo "Constant SITE_NAME is not defined."; } ?>
- The defined() function returns true if the constant exists and false otherwise.
Summary of PHP Constants:
Method | Description | Example |
---|---|---|
define() | Defines a constant at runtime | define(“NAME”, “value”); |
const | Defines a constant at compile-time | const NAME = “value”; |
defined() | Checks if a constant exists | defined(“NAME”); |
PHP_VERSION | Predefined constant for PHP version | PHP_VERSION |
__FILE__ | Magic constant for the current file path | __FILE__ |
PHP_OS | Predefined constant for the operating system | PHP_OS |
Constant Arrays | Array constants introduced in PHP 5.6+ | define(“ARRAY”, […]); |
Conclusion
Constants in PHP are an essential feature for defining immutable values in your application, such as configuration settings or global values.
Here’s a summary of what we covered:
- Defining constants using define() and const.
- Case sensitivity of constants and the deprecated case-insensitive feature.
- Predefined PHP constants and magic constants that provide useful system information.
- Constant arrays for storing multiple values in an immutable array.
- Checking if constants exist using defined().