PHP Constants Tutorial with Examples

In PHP, constants are used to define values that cannot be changed during the execution of a script. They are different from variables, as their values remain constant and immutable once defined. Constants are especially useful for storing fixed values like configuration options, mathematical constants, or any data that should remain unchanged.

In this tutorial, we will cover:

1. What are PHP Constants?

A constant is an identifier (name) for a simple value. Once a constant is defined, it cannot be changed or undefined during the script’s execution.

Constants are useful when you want to store data that should remain the same throughout your program, such as settings, URLs, or mathematical constants.

Characteristics of Constants:

They are global and accessible throughout the entire script.
They do not use a dollar sign ($) like variables.
Constants cannot be changed once they are defined.

2. Defining Constants in PHP

Using the define() Function
The define() function is commonly used to create a constant in PHP. It takes two parameters:

The name of the constant.
The value of the constant.

Syntax:

define('CONSTANT_NAME', value);

Example:

<?php
define('SITE_NAME', 'MyWebsite');
define('SITE_URL', 'https://www.mywebsite.com');

echo SITE_NAME; // Outputs: MyWebsite
echo SITE_URL; // Outputs: https://www.mywebsite.com
?>

In this example, the constants SITE_NAME and SITE_URL are defined, and their values are accessed using their names (without $).

3. Rules for Naming Constants

When naming constants, follow these rules:

Constant names should be all uppercase by convention, though PHP is case-insensitive for constant names by default.
Constant names can contain letters, numbers, and underscores (_).
Constant names cannot start with a number.
Constants do not have a $ symbol in front, unlike variables.

4. Accessing Constants

You can access a constant by simply using its name. Unlike variables, you don’t need a $ symbol to access constants.

Example:

<?php
define('PI', 3.14159);
echo PI; // Outputs: 3.14159
?>

 

Case Sensitivity in Constants:

By default, constants are case-sensitive. However, you can make them case-insensitive by passing a third optional parameter as true in the define() function.

Example (Case-insensitive constant):

<?php
define('GREETING', 'Hello, World!', true);
echo GREETING; // Outputs: Hello, World!
echo greeting; // Outputs: Hello, World! (because it's case-insensitive)
?>

 

5. Magic Constants

PHP provides several magic constants that change depending on where they are used. These constants start with two underscores (__) and provide useful information such as file paths, function names, and line numbers.

Common Magic Constants:
__LINE__ – The current line number of the file.
__FILE__ – The full path and filename of the file.
__DIR__ – The directory of the file.
__FUNCTION__ – The name of the function.
__CLASS__ – The name of the class.
__METHOD__ – The name of the class method.
__NAMESPACE__ – The name of the current namespace.

Example:

<?php
echo "This is line number " . __LINE__; // Outputs: This is line number 1 (or the current line number)

echo "The file is located at: " . __FILE__; // Outputs: The full path and filename of the file
?>

 

Magic constants are especially useful when debugging or when dynamically generating information about the current code’s structure.

6. Using the define() Function

Defining Scalar Constants:

The define() function is commonly used to define constants that store scalar values like integers, strings, or booleans.

Example:

<?php
define('MAX_USERS', 100); // Integer constant
define('SITE_ACTIVE', true); // Boolean constant

echo MAX_USERS; // Outputs: 100
echo SITE_ACTIVE; // Outputs: 1 (true is printed as 1)
?>

Defining Array Constants (PHP 7+):

Starting from PHP 7, you can define constants that store arrays.

Example:

<?php
define('COLORS', ['Red', 'Green', 'Blue']);
echo COLORS[0]; // Outputs: Red
?>

Here, COLORS is an array constant, and you can access its elements just like a regular array.

7. Using the const Keyword

Another way to define constants in PHP is by using the const keyword. This method can only be used to define constants in the global scope or inside classes.

Syntax:

const CONSTANT_NAME = value;

Example (Global Scope):

<?php
const GREETING = 'Hello, World!';
echo GREETING; // Outputs: Hello, World!
?>

Example (Inside Classes):

You can define constants within classes, and they are accessed using the class name and the scope resolution operator (::).

 

<?php
class Car {
const WHEELS = 4;

public function getWheels() {
return self::WHEELS; // Accessing the constant from within the class
}
}

echo Car::WHEELS; // Outputs: 4

$car = new Car();
echo $car->getWheels(); // Outputs: 4
?>

 

In this example, WHEELS is a constant defined within the Car class, and it can be accessed both from outside the class and within it using self::WHEELS.

8. Example Use Cases for Constants

1. Defining Application Settings

Constants are often used to store values that define the configuration of an application, such as database settings or API keys.

 

<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'my_database');

// Example usage in database connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
?>

 

2. Defining Mathematical Constants

Mathematical constants like PI or E can be stored using PHP constants.

 

<?php
define('PI', 3.14159);
define('E', 2.71828);

echo "Value of PI: " . PI; // Outputs: Value of PI: 3.14159
echo "Value of E: " . E; // Outputs: Value of E: 2.71828
?>

 

3. Defining URL Paths and Directory Paths

You can define constants to store URLs or file paths to avoid hardcoding them multiple times.

 

<?php
define('BASE_URL', 'https://www.example.com/');
define('UPLOAD_DIR', '/var/www/uploads/');

echo BASE_URL . 'about.php'; // Outputs: https://www.example.com/about.php
echo "Files are uploaded to: " . UPLOAD_DIR; // Outputs: Files are uploaded to: /var/www/uploads/
?>

 

Conclusion

PHP constants are a powerful way to define immutable values that can be accessed throughout your script or application.

They help improve code maintainability and readability by keeping important values centralized and unmodifiable.

Key Takeaways:

Constants are defined using the define() function or const keyword.
Once defined, a constant’s value cannot be changed.
Constants do not have a $ symbol in front of them.
They are often used for fixed configuration values, mathematical constants, and global settings.
Magic constants in PHP provide useful metadata about the script’s environment.

By effectively using constants in your PHP code, you can create cleaner, more robust applications!

Related posts

PHP Static Methods: A Tutorial with Examples

PHP Deleting Files: A Tutorial with Examples

PHP Copying Files: A Tutorial with Examples