If you have been following this PHP tutorial series from the beginning, you already know how PHP variables work. But in this fourth tutorial, we will explore a concept that behaves almost like variables but has one major difference — they cannot be changed. These special values are known as Constants in PHP. In this article, we will break down everything about PHP constants in a very simple and friendly way so that even a complete beginner can understand them without confusion.
What Is a Constant Variable in PHP?
A constant variable in PHP is a type of variable whose value cannot be changed once it is assigned. Unlike regular variables that can store different values at different times, constants remain the same throughout the entire script. You define them once, and then they stay fixed — just like their name suggests.This is extremely useful when you want to store a value that should never change, such as:
- Tax rate
- Website name
- API keys
- Database configuration
- Maximum limits
One easy way to think about constants is this:
A constant is like writing something in permanent ink instead of pencil. Once written, it stays the same.
Constants add reliability and readability to your code because they clearly indicate that the value stored inside is not meant to be modified at any point.
Why Do We Need Constants in PHP?
There are many situations in programming where you want to keep certain values fixed throughout the application. Changing these values by accident can break your entire project. That is why PHP allows constants—to protect such values from unexpected modification.
For example, imagine a situation where you store your website name in a variable and later accidentally overwrite it using another part of the code. This unintentional change could cause unexpected issues. But if you use a constant, PHP will not allow that value to change, which helps maintain consistency and stability in your project.
Another important reason to use constants is readability. When other developers see constant names written in capital letters, they immediately understand that this value is not supposed to change.
How to Create a Constant in PHP?
PHP provides two different ways to create constants:
- Using the define() function
- Using the const keyword
1. Creating a Constant Using define() Function
The define() function is the most traditional and popular way to create constants in PHP. It has been available since the early versions of PHP and is still widely used today.
define("CONSTANT_NAME", value, case_insensitive);
Here is what each part means:
CONSTANT_NAME → The name of your constant (written in uppercase by convention).
value → The data you want to store inside the constant.
case_insensitive → An optional parameter; if set to true, the constant name becomes case-insensitive.
Explanation:
In this example, we created a constant named SITE_NAME and stored the text "My Tutorial Website" inside it. When you echo the constant, it prints the value. The important part is that this value cannot change anywhere in the script, even if someone tries to overwrite it.
Using define() is simple and powerful, especially when you want flexibility and older PHP version support. Most beginner-friendly PHP tutorials prefer define() because it works in almost every PHP environment.
2. Creating a Constant Using the const Keyword
The second method to create constants is by using the const keyword. This approach is more modern and also more strict compared to define(). It behaves somewhat like variable declaration but with the added advantage that the assigned value can never change.
define("CONSTANT_NAME", value, case_insensitive);
Explanation:
Here we defined a constant named "GREETING" using the const keyword. Once defined, PHP will not allow you to change the value of "GREETING" anywhere in the script. This method is often used in object-oriented PHP (OOP) because it allows defining class constants.
The key difference here is that constants created with const are defined at compile time, which means they are slightly faster and more error-proof compared to define().
Difference Between define() and const
Although both methods create constants, there are important differences that every PHP developer should know. Understanding these differences will help you decide which method to use in different situations.
1. Difference Between define() and const
define() is processed when the code is running. const is processed before the code actually runs (compile time).
2. const Cannot Be Used Inside Conditional Statements
For example, this will work: define("NAME", "John");
if (true) {
const NAME = "John"; // ❌ not allowed
}
3. const Can Be Used Inside Classes
In PHP, "const" Inside Classes is popular because it provides safe, predictable and performant class-level values.
4. define() Allows Dynamic Values
In PHP, define() can be used with variables, functiona calls, or expression because it is executed at runtime.
$prefix = "APP";
define($prefix . "_NAME", "My Application");
echo APP_NAME; // My Application
Rules for Naming PHP Constants
Just like variables, constants also follow certain naming rules. These rules ensure that your constant names are clean, readable, and error-free.
Important Naming Rules:
- Constant names should not start with a number.
- Only letters, numbers, and underscores should be used.
- No spaces or special characters are allowed.
- Best practice: Use all uppercase letters for constant names.
- Use underscores (_) for multiple words, e.g., MAX_VALUE.
- Following these rules makes your code more consistent and easier for others to read.
Types of Constants in PHP
Although PHP constants are straightforward, they can be divided into two main categories based on their behavior and usage.
1. define() Allows Dynamic Values
These are the constants you create using:
- define()
- const
These constants can hold "Strings", "Integers", "Floats", "Booleans", "Arrays". User-defined constants are extremely helpful when building applications with predictable values.
2. Predefined Constants in PHP
PHP also comes with a large number of built-in constants that help you access system-level information. These constants are readily available and you don’t need to define them yourself.
Common Examples:
- PHP_VERSION → Current PHP version
- PHP_INT_MAX → Maximum integer supported
- __FILE__ → The full path of the current file
- __LINE__ → Current line number
- E_ALL → All error reporting levels
These predefined constants are auto-generated by PHP to help developers work with environment-related information.
Can You Change the Value of a Constant?
The simple answer is: No, you cannot change the value of a constant. Once you define a constant, PHP permanently locks its value for the entire script. If you try to redefine or modify a constant, PHP will show an error or ignore the new value.
This behavior is exactly what makes constants useful because they protect important values in your application from being changed accidentally. If you need a value that changes frequently, then use a normal variable instead of a constant.
Advantages of Using Constants in PHP
- Using constants brings several benefits to your code, especially in larger projects. Here are some major advantages:
- Constants keep important values fixed, which makes your application more reliable and stable.
- When other developers see uppercase constant names, they instantly understand that this value cannot change.
- Constants are globally accessible, even inside functions and classes.
- If you store important configuration values in constants, you only need to update them in one place.
- Constants defined using const can improve performance because they are evaluated during compilation.
Conclusion: Why You Should Use Constants in PHP
Constants may look simple on the surface, but they play a very important role in PHP programming. They protect critical values from modification, improve code readability, and make your entire application more organized and reliable. Whether you are building small scripts or large applications, constants give your project structure and stability.