PHP Constants – Complete Beginner Tutorial
While variables are designed to store values that may change during program execution, constants store values that remain the same. Once a constant has been created, its value cannot be modified or deleted during the execution of the script.
Constants are widely used in PHP applications to store configuration values such as website names, company information, API keys, version numbers, database settings, and file paths.
What is a Constant?
A constant is a named value that cannot be changed once it has been defined.
Think of a constant as information that should always remain the same throughout your application.
Examples include:
- Your company name
- Website URL
- VAT or Tax Rate
- Application Version
- Database Host
- API Keys
Creating a Constant using define()
The most common way to create a constant is by using the define() function.
<?php
define("SITE_NAME","PHP.Exalogics.com");
echo SITE_NAME;
?>
Output
PHP.Exalogics.com
Notice that constants are used without the $ symbol.
Constant Naming Rules
| Rule | Example |
|---|---|
| No dollar sign | SITE_NAME |
| Usually uppercase | MAX_USERS |
| Can contain numbers | VERSION2 |
| Cannot begin with a number | 2VERSION ❌ |
| Use underscores | DATABASE_HOST |
Why Use Constants?
Imagine your website contains your company name on hundreds of pages.
Instead of writing the name everywhere, define it once.
define("COMPANY","Travel & Culture Services");
Whenever you need it:
echo COMPANY;
If you ever need to change the company name, you only update it in one place.
Constants vs Variables
| Variable | Constant |
|---|---|
| Starts with $ | No $ sign |
| Can change value | Cannot change |
| Created using = | Created using define() or const |
| Case-sensitive | Usually uppercase |
Using the const Keyword
PHP also allows constants to be created using the const keyword.
<?php
const VERSION = "1.0";
echo VERSION;
?>
Both define() and const are widely used in modern PHP.
Constants Inside Expressions
Constants can be combined with text just like variables.
<?php
define("SITE","PHP.Exalogics.com");
echo "Welcome to " . SITE;
?>
Output
Welcome to PHP.Exalogics.com
Checking Whether a Constant Exists
The defined() function checks whether a constant has already been created.
<?php
define("COUNTRY","Pakistan");
if(defined("COUNTRY"))
{
echo "Constant exists.";
}
?>
Output
Constant exists.
Tip:
Using defined() helps prevent errors when including multiple configuration files.
Real World Example
Almost every professional PHP project has a configuration file that stores constants.
<?php
define("SITE_NAME","Travel & Culture");
define("SUPPORT_EMAIL","info@example.com");
define("PHONE","+92-321-1234567");
define("CURRENCY","USD");
?>
These values remain unchanged throughout the application and can be accessed from any included file.
Advantages of Constants
- Prevent accidental modification.
- Improve code readability.
- Centralize configuration values.
- Reduce repeated code.
- Simplify application maintenance.
- Useful for application settings and environment values.
Best Practice:
Use constants for values that should never change while your program is running, such as version numbers, application names, configuration values, and fixed URLs. Use variables for information that changes, such as user input, prices, or dates.
Magic Constants in PHP
PHP includes several built-in constants known as Magic Constants. Their values change depending on where they are used, making them extremely useful for debugging, logging, and determining file locations.
| Magic Constant | Description |
|---|---|
| __FILE__ | Returns the full path and filename of the current file. |
| __DIR__ | Returns the directory of the current file. |
| __LINE__ | Returns the current line number. |
| __FUNCTION__ | Returns the current function name. |
| __CLASS__ | Returns the current class name. |
| __METHOD__ | Returns the current class method. |
| __NAMESPACE__ | Returns the current namespace. |
| __TRAIT__ | Returns the current trait name. |
Using __FILE__
This constant returns the complete path to the current PHP file.
<?php
echo __FILE__;
?>
Example Output:
/var/www/html/index.php
Using __DIR__
Returns the directory containing the current file.
<?php
echo __DIR__;
?>
This is especially useful when including other PHP files.
require_once __DIR__ . "/config.php";
Using __LINE__
<?php
echo __LINE__;
?>
PHP displays the line number where the statement appears.
This is useful when debugging large applications.
Constants Inside Classes
Classes can contain their own constants.
<?php
class Website
{
const NAME = "PHP.Exalogics.com";
}
echo Website::NAME;
?>
Output:
PHP.Exalogics.com
Using Constants for Configuration
Most professional PHP applications have a configuration file.
<?php
define("DB_HOST","localhost");
define("DB_NAME","travel");
define("DB_USER","root");
define("DB_PASSWORD","password");
define("SITE_URL","https://php.exalogics.com");
?>
Every page can include this configuration file instead of repeating the same values.
Real World Example
Imagine you’re building an online booking system.
<?php
define("COMPANY","Travel & Culture Services");
define("EMAIL","info@travel-culture.com");
define("PHONE","+92-321-2424778");
define("DEFAULT_CURRENCY","USD");
echo COMPANY;
?>
If any of these values change in the future, you only update one file.
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Using $ before constants | Constants never use a dollar sign. |
| Trying to change a constant | Constants cannot be modified after creation. |
| Using lowercase names | Use uppercase names for readability. |
| Using variables for configuration | Use constants instead. |
Best Practices
- Use uppercase letters for constant names.
- Group configuration constants into one file.
- Use descriptive names.
- Avoid hardcoding repeated values throughout your application.
- Use __DIR__ for including files.
- Keep sensitive configuration outside the public web directory whenever possible.
Practice Exercises
- Create a constant containing your website name.
- Create a constant for today’s currency.
- Create a constant containing your country.
- Display all constants using echo.
- Use defined() to check whether a constant exists.
- Display the current filename using __FILE__.
- Display the current directory using __DIR__.
Summary
Constants are ideal for storing values that never change while a PHP program is running. They improve readability, simplify maintenance, and reduce the risk of accidental changes. Magic constants provide additional information about your code and are invaluable for debugging and building professional applications.
Frequently Asked Questions
What is the difference between a variable and a constant?
A variable can change during program execution, while a constant keeps the same value for the entire script.
Do constants use a dollar sign?
No. Constants are referenced by name only.
Which is better, define() or const?
Both are valid. const is commonly used within classes and for simple declarations, while define() is often used in configuration files.
What are magic constants?
Magic constants are predefined constants that automatically return information such as the current file, directory, line number, class, or function.
Can constants store arrays?
Yes. Modern versions of PHP allow constants to contain arrays using the const keyword.
Quick Challenge
Create a file named config.php that contains constants for:
- Website Name
- Website URL
- Support Email
- Telephone Number
- Current Version
Include this file in another PHP page and display all the constants.
Next Tutorial
Now that you understand variables, data types, and constants, it’s time to perform calculations and comparisons using PHP Operators.
Next: PHP Operators