Understanding constants in PHP
In this article, we will explore how to declare and use constants in PHP, covering key concepts and practical examples.
We will also examine the differences between the two ways to define constants: the define()
function and the const
keyword.
Additionally, you will learn about array constants—how to declare arrays as constants in PHP.
PHP Constants
What Is a Constant in PHP?
In PHP, a constant is an identifier (name) for a simple value that, once defined, cannot be changed. Constants retain their values throughout the execution of the program and are typically used to represent values that remain the same across different parts of the code.
How to Declare Constants in PHP
You can declare constants in two primary ways:
- Using the
define()
function - Using the
const
keyword inside a class
/* Declaring a global constant using define() */
define('GLOBAL_CONSTANT', 200);
echo GLOBAL_CONSTANT; // 200
/* Declaring a class constant using the const keyword */
class MyClass {
const CONSTANT = 'constant value';
function showConstant() {
echo self::CONSTANT . "\n";
}
}
echo MyClass::CONSTANT; // 'constant value'
$class = new MyClass();
$class->showConstant(); // 'constant value'
Constants are typically written in uppercase letters, and underscores (_
) are used to separate words for better readability. They are commonly used for fixed configuration values, roles, status codes, and similar elements that shouldn't change during execution.
Like PHP Superglobals, constants are available in the global scope and can be accessed anywhere in your code.
Why Constants Matter: Practical Benefits
Since constants cannot be reassigned after being defined, they are ideal for representing values that must remain unchanged throughout the program. Defining such values as constants offers several advantages:
- Improves code readability and maintainability
- Ensures consistency and stability
- Helps prevent bugs and unintended changes
Improves code readability and maintainability
Using constants instead of hard-coded values makes your code easier to understand and maintain. For example, you can define meaningful status codes like this:
define('STATUS_ACTIVE', 1);
define('STATUS_INACTIVE', 2);
define('STATUS_ARCHIVED', 3);
This approach makes the code more self-explanatory and easier to manage later.
Ensures consistency and stability
Because constants cannot be changed, they help protect against accidental modifications. When the same value is used in multiple places, defining it as a constant ensures consistency across the entire application.
define('MAX_LOGIN_ATTEMPTS', 5);
This value can then be used wherever login attempts are checked, without the risk of being altered elsewhere in the code.
Helps prevent bugs and unintended changes
By making values immutable, constants reduce the likelihood of bugs caused by unintended changes. Consider the following example:
// Using a constant
define('TAX_RATE', 0.1);
$totalAmount = $subTotal + ($subTotal * TAX_RATE);
// Without a constant
$taxRate = 0.1;
$totalAmount = $subTotal + ($subTotal * $taxRate);
이러한 이점들은 상수의 중요성을 강조하고, 프로그램의 안정성과 가독성을 향상시키는 데에 큰 도움이 됩니다. 상수를 적절히 활용하여 코드의 유지보수성과 품질을 높일 수 있습니다.
Constants vs. Variables
The key difference between constants and variables is mutability.
Variables can be reassigned at any time, whereas constants are immutable after their initial assignment. This makes constants especially useful for representing fixed values that should not change.
Summary: Key Advantages of Constants
- Ideal for representing values that must remain unchanged
- Help prevent bugs caused by accidental value changes
- Using uppercase names improves readability and clarity
- Some features may behave differently depending on the PHP version—be mindful of version-specific behavior when working with constants
In this section, you’ve learned the concept and importance of constants in PHP, including how they differ from variables.
In the next section, we'll explore how to declare and use constants in more detail.
Declaring and Using Constants in PHP
There are two main ways to declare constants in PHP: using the define()
function and the const
keyword. In this section, we’ll take a closer look at each method and also discuss the scope of constants in PHP.
Declaring Constants with the define()
Function
The define()
function is used to declare global constants. This method is available in PHP 4 and later.
Syntax
define(string $constant_name, mixed $value, bool $case_insensitive = false): bool
Parameters
$constant_name |
The name of the constant. Must be a string. |
---|---|
$value |
The value to assign to the constant. In PHP 5, it must be a scalar value (int , float , string , bool , or null ). In PHP 7 and later, arrays are also allowed. |
$case_insensitive |
Whether the constant name should be case-insensitive. If set to true , the constant can be referenced regardless of case. Default behavior is case-sensitive—so CONSTANT and Constant are treated as different.
Warning: This option has been deprecated as of PHP 7.3.0 and is no longer allowed in PHP 8.0.0 and later. Passing true will trigger a warning. |
Return Value
Returns true
on success, or false
on failure.
Example Usage
define('MY_CONSTANT', 10);
echo MY_CONSTANT; // Outputs: 10
In the example above, MY_CONSTANT
is accessible from anywhere in the global scope.
Declaring Constants with the const
Keyword
The const
keyword can be used to declare class-level constants. This method is available from PHP 5 onward.
class MyClass {
const CLASS_CONSTANT = 100;
public function getConstantValue() {
return self::CLASS_CONSTANT;
}
}
echo MyClass::CLASS_CONSTANT; // Outputs: 100
In this example, CLASS_CONSTANT
is accessible inside the class using self::
and externally using the class name and scope resolution operator ::
.
Scope of Constants in PHP
define() |
Constants declared with define() are accessible globally from anywhere in the script. |
---|---|
const |
Constants declared with const are scoped to the class in which they are defined. Access from within the class is done using self::CONSTANT_NAME , and access from outside the class requires the class name and :: operator. |
Scope Example
define()
define('GLOBAL_CONSTANT', 200);
class AnotherClass {
public function getConstantValue() {
return GLOBAL_CONSTANT;
}
}
echo GLOBAL_CONSTANT; // Outputs: 200
$anotherClass = new AnotherClass();
echo $anotherClass->getConstantValue(); // Outputs: 200
Since GLOBAL_CONSTANT
was defined using define()
, it’s available throughout the global scope—even inside classes.
const
class MyClass {
const CLASS_CONSTANT = 100;
}
echo MyClass::CLASS_CONSTANT; // Outputs: 100
// Attempting to access it directly without the class name will result in a warning:
// echo CLASS_CONSTANT; // Warning: Use of undefined constant CLASS_CONSTANT
Constants declared with const
must be accessed using the class name or self::
syntax. Direct access without proper qualification will result in a warning.
Comparison of define()
and const
Feature | define() Function |
const Keyword |
---|---|---|
Declaration | Declared in the global scope | Declared within a class |
Access | Globally accessible throughout the script | Accessible within the class using self:: , and externally using the class name and :: |
Case Sensitivity | Case-sensitive by default; case-insensitive allowed before PHP 8.0 | Always case-sensitive |
Timing | Evaluated at runtime; useful when conditionally defining constants | Evaluated at compile time; cannot be used inside conditional blocks |
PHP Version | Available since PHP 4 | Available since PHP 5 |
Defining Array Constants in PHP
Starting with PHP 7, you can assign arrays as values when declaring constants using the define()
function.
In earlier versions of PHP (before 7.0), constant values were limited to scalar types only—such as integers, floats, strings, booleans, and null
.
This enhancement was introduced to give developers more flexibility when working with constants. Let's take a look at an example:
define('FRUITS', ['apple', 'orange', 'banana']);
echo FRUITS[0]; // Output: apple
Array Constants Are Read-Only
Constants that hold array values are immutable. Attempting to modify any element of a constant array will result in a fatal error.
define('FRUITS', ['apple', 'orange', 'banana']);
FRUITS[0] = 'grape'; // Fatal Eror
As shown above, trying to change the value of an element within a constant array will trigger an error. While regular arrays are mutable, arrays assigned to constants are treated as read-only.
This behavior enforces the principle that constants in PHP are meant to represent fixed values that do not change after being defined.
Important Note:
You cannot use the const
keyword to declare an array constant—not even in PHP 7 or later.
The const
keyword only allows scalar values. Complex data types like arrays or objects are not permitted.