PHP Constants and define

Part of the course: php for beginners

PHP Constants and define

PHP Constants and define

PHP Constants and define

1. Introduction to Constants in PHP

1.1 What Are Constants?

In PHP, a constant is a name or an identifier for a simple value that cannot change during the execution of the script. Unlike variables, once a constant is defined, its value is permanent and cannot be altered. Constants are commonly used to store configuration settings, fixed values, or other information that should remain the same throughout the application.

Key points about constants:

  • Constants do not start with a $ symbol like variables.

  • They can store strings, numbers, or boolean values.

  • Constants are globally accessible after being defined.

Example:

define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Output: MyWebsite

1.2 Difference Between Variables and Constants

Feature Variables Constants
Symbol Starts with $ No $ symbol
Value Can change Cannot change
Scope Depends on declaration Always global
Definition Using $var = value; Using define() or const

Example:

$color = "red";
$color = "blue"; // variable value can change
define(“PI”, 3.14);
PI = 3.1416; // ❌ Error: constants cannot be changed

1.3 Advantages of Using Constants

  1. Stability: Values do not accidentally change during execution.

  2. Global Access: Once defined, constants can be accessed anywhere in the script.

  3. Improved Readability: Using meaningful constant names makes code easier to understand.

  4. Configuration Management: Ideal for settings like database credentials, file paths, or API keys.

Example:

define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "password");

Constants like these make it easy to manage configuration settings without risking accidental changes.

2. Defining Constants

2.1 Using the define() Function

In PHP, the most common way to define a constant is by using the define() function. This function allows you to create a constant with a specific name and value that cannot change during script execution.

The basic syntax is:

define("CONSTANT_NAME", value);
  • CONSTANT_NAME is the name of the constant.

  • value is the value you want to assign. It can be a string, number, or boolean.

Once defined, you can use the constant anywhere in your script without the $ symbol.

2.2 Syntax and Parameters of define()

The full syntax of define() looks like this:

define(string $name, mixed $value, bool $case_insensitive = false)
  • $name: The name of the constant (usually uppercase by convention).

  • $value: The value assigned to the constant (string, number, or boolean).

  • $case_insensitive (optional, default false): If set to true, the constant name will be case-insensitive. This means MY_CONST and my_const would be treated as the same.

Example:

define("SITE_URL", "https://example.com");
define("MAX_USERS", 100);
define("IS_ACTIVE", true);
define("GREETING", "Hello World", true); // case-insensitive (less common)

2.3 Examples of define()

Example 1: Simple String Constant

define("APP_NAME", "MyApp");
echo APP_NAME; // Output: MyApp

Example 2: Numeric Constant

define("PI", 3.14159);
echo PI; // Output: 3.14159

Example 3: Boolean Constant

define("DEBUG_MODE", true);
if(DEBUG_MODE) {
echo "Debugging is enabled";
}

Example 4: Case-insensitive Constant (optional usage)

define("WELCOME_MESSAGE", "Welcome!", true);
echo welcome_message; // Output: Welcome! (case-insensitive)

Key Points to Remember:

  • Constants cannot be changed once defined.

  • No $ is used when referring to a constant.

  • By convention, constant names are uppercase with underscores.

  • Constants are global and can be accessed anywhere in the script.

 

3. Using the const Keyword

3.1 Difference Between define() and const

In PHP, constants can also be declared using the const keyword, which was introduced in PHP 5.3. While define() is a function, const is a language construct. Here are the main differences:

Feature define() const
Type Function Language construct
Scope Can be defined anywhere, including inside functions (global constant) Must be defined at top-level or inside classes (cannot be inside functions or loops in PHP < 7)
Value types Can be scalar values (string, int, float, boolean) Can be scalar values and arrays (PHP 5.6+ for arrays)
Case sensitivity Optional (via third parameter) Always case-sensitive
Context Runtime Compile-time

Example using const:

const SITE_NAME = "MyWebsite";
const MAX_USERS = 500;
const SETTINGS = ["theme" => "dark", "lang" => "en"]; // PHP 5.6+

Unlike define(), const cannot use expressions like function calls or concatenation in its value. For example, this is invalid:

const SITE_URL = "https://" . "example.com"; // ❌ Error

3.2 When to Use const vs define()

  • Use const when:

    • Defining constants inside classes.

    • You want compile-time constants.

    • You need array constants (PHP 5.6+).

    • Case sensitivity is required.

Example in a class:

class Config {
const DB_HOST = "localhost";
const DB_USER = "root";
}
echo Config::DB_HOST; // Output: localhost
  • Use define() when:

    • You need runtime constants.

    • You want optional case-insensitive constants.

    • You are defining constants outside class scope and using dynamic values.

Example with define():

$env = "development";
define("ENVIRONMENT", $env); // Works with variables

4. Constant Naming Rules

4.1 Case Sensitivity

By default, constants in PHP are case-sensitive, meaning the name must match exactly how it was defined.

Example:

define("SITE_NAME", "MyWebsite");

echo SITE_NAME; // Output: MyWebsite
echo site_name; // ❌ Error: Undefined constant

  • If you use const to define a constant, it is always case-sensitive.

  • With define(), you can optionally make a constant case-insensitive by passing true as the third parameter:

define("GREETING", "Hello!", true);
echo GREETING; // Output: Hello!
echo greeting; // Output: Hello! (case-insensitive)

Note: Case-insensitive constants are rarely used and not recommended in modern PHP because they can reduce code clarity.

4.2 Naming Conventions

Following a clear naming convention improves readability and maintainability of your code. Common conventions for constants in PHP include:

  1. Uppercase Letters with Underscores

    • Use uppercase letters for the constant name.

    • Separate words with underscores.

Example:

define("MAX_USERS", 100);
const SITE_URL = "https://example.com";
  1. Meaningful Names

    • Constant names should clearly describe the value or purpose.

Example:

define("DB_HOST", "localhost"); // Good
define("X", "localhost"); // Poor
  1. Avoid Starting with Numbers

    • Constant names cannot begin with a number.

define("123_CONSTANT", "value"); // ❌ Invalid
  1. Consistency

    • Always use the same style throughout your project. This avoids confusion and makes code easier to maintain.

 

 

5. Accessing Constants

5.1 Accessing Global Constants

Once a constant is defined using either define() or const, it becomes globally accessible throughout the script — meaning it can be used in functions, classes, or included files without redefinition.

Example:

define("SITE_NAME", "MyWebsite");

function showSiteName() {
echo SITE_NAME; // Accessible inside a function
}

showSiteName(); // Output: MyWebsite
echo SITE_NAME; // Output: MyWebsite

Key Points:

  • Global constants do not require a $ symbol when accessed.

  • They can be used anywhere after being defined.

  • Constants are automatically available in all scopes (unlike variables that may need global or use keywords).

You can also check if a constant is defined before using it:

if (defined("SITE_NAME")) {
echo SITE_NAME;
}

5.2 Accessing Class Constants

Constants can also be defined inside classes using the const keyword.
These are known as class constants and are accessed using the scope resolution operator (::).

Example:

PHP Constants and define
class Config {
const DB_HOST = "localhost";
const DB_USER = "root";
const DB_PASS = "password";
}
echo Config::DB_HOST; // Output: localhost

You can also access class constants from within the class itself using:

  • self::CONSTANT_NAME (for the same class)

  • parent::CONSTANT_NAME (for inherited constants from a parent class)

Example:

class BaseConfig {
const APP_VERSION = "1.0";
}
class App extends BaseConfig {
const APP_NAME = “MyApp”;public function showInfo() {
echo self::APP_NAME . ” – Version: “ . parent::APP_VERSION;
}
}$app = new App();
$app->showInfo(); // Output: MyApp – Version: 1.0

Summary:

  • Global constants (using define() or const) can be accessed anywhere directly by name.

  • Class constants (using const inside classes) are accessed via ClassName::CONSTANT_NAME.

  • Class constants are automatically static, meaning they don’t need an object instance to be accessed.

  • Use self::, parent::, or static:: inside classes to refer to constants appropriately.

 

6. Magic Constants in PHP

6.1 Overview of Built-in Magic Constants

PHP provides several built-in constants known as magic constants.
These are special constants that change their value depending on where they are used in the script.

Unlike user-defined constants (created using define() or const), magic constants are automatically provided by PHP and are always available without any prior definition.

Magic constants are extremely useful for debugging, logging, and dynamically handling file paths or class names in large projects.

All magic constants in PHP begin and end with two underscores (__) — for example, __LINE__ or __FILE__.

6.2 Commonly Used Magic Constants

Here are the most frequently used magic constants and what they represent:

Magic Constant Description Example Output
__LINE__ Returns the current line number of the file where it is used. If used on line 10 → 10
__FILE__ Returns the full path and filename of the file. /var/www/html/index.php
__DIR__ Returns the directory path of the file. /var/www/html
__FUNCTION__ Returns the name of the current function. myFunction
__CLASS__ Returns the name of the current class (including namespace if applicable). App\Controllers\User
__METHOD__ Returns the name of the current class method. User::login
__NAMESPACE__ Returns the current namespace name. App\Models
__TRAIT__ Returns the name of the current trait (if used). LoggerTrait

Examples:

echo __LINE__; // Displays the current line number
echo __FILE__; // Displays the full path of this file
echo __DIR__; // Displays the directory of this file

Example inside a class:

class Test {
public function showInfo() {
echo __CLASS__ . "\n"; // Output: Test
echo __METHOD__ . "\n"; // Output: Test::showInfo
echo __FUNCTION__ . "\n"; // Output: showInfo
}
}
$test = new Test();
$test->showInfo();

Why Use Magic Constants?

  1. Debugging: You can easily log where an error occurs using __FILE__ and __LINE__.

  2. Dynamic File Paths: __DIR__ helps when including or requiring files without hardcoding paths.

  3. Code Maintenance: You can reference class names or methods automatically using __CLASS__ or __METHOD__.

Example (Debugging):

echo "Error in file: " . __FILE__ . " on line " . __LINE__;

Summary:

  • Magic constants are built-in and context-sensitive.

  • They start and end with double underscores (__).

  • They help in debugging, logging, and managing file paths.

  • Their values are determined automatically by PHP during runtime.

 

7. Practical Examples and Use Cases

Constants are very useful in real-world PHP projects. They help make code more organized, consistent, and secure, especially for configuration management, environment control, and debugging.
Let’s look at some common scenarios where constants are used effectively.

7.1 Configuration Settings

One of the most common uses of constants is for application configuration.
Instead of hardcoding values throughout the code, you can define constants once and reuse them everywhere.

Example:

define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "password");
define("DB_NAME", "my_database");
define("SITE_URL", "https://example.com");
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);if (!$conn) {
die(“Connection failed: “ . mysqli_connect_error());
}

Why use constants here?

  • Configuration values remain consistent.

  • Easier to update — just change the constant once.

  • Prevents accidental modification of critical values.

7.2 Environment-Based Constants

Constants are ideal for setting environment-specific configurations, such as development, testing, or production modes.

Example:

define("ENVIRONMENT", "development");

if (ENVIRONMENT === “development”) {
error_reporting(E_ALL);
ini_set(“display_errors”, 1);
define(“DB_HOST”, “localhost”);
} else {
error_reporting(0);
ini_set(“display_errors”, 0);
define(“DB_HOST”, “prod-db-server”);
}

echo “Running in “ . ENVIRONMENT . ” mode.”;

Benefits:

  • Makes it easy to switch between environments without editing multiple files.

  • Helps maintain different configurations for development and production.

  • Improves application security by hiding sensitive settings in production.

7.3 Debugging and Logging

Constants are also very helpful for debugging and error logging.
You can use constants to control whether debugging is active and to store log file paths.

Example:

define("DEBUG_MODE", true);
define("LOG_FILE", __DIR__ . "/app.log");
function logMessage($message) {
if (DEBUG_MODE) {
$time = date(“Y-m-d H:i:s”);
file_put_contents(LOG_FILE, “[$time] $message\n”, FILE_APPEND);
}
}logMessage(“Application started”);
logMessage(“User logged in”);

Explanation:

  • DEBUG_MODE determines whether debugging is enabled.

  • LOG_FILE defines the path of the log file.

  • You can easily turn debugging on/off by changing just one constant.

Advantages:

  • Centralized control of debugging behavior.

  • Easier to maintain logs for troubleshooting.

  • Keeps the production environment clean and secure.

Summary:

  • Use constants for configuration, environment control, and debugging.

  • Constants make code more readable, reliable, and maintainable.

  • They reduce errors by ensuring important values cannot be changed accidentally.

 

8. Best Practices for Using Constants

Constants are powerful tools in PHP that make your code more stable and reliable. However, to get the most benefit, it’s important to follow best practices related to maintainability, security, and code readability.

8.1 Maintainability

Maintainability means keeping your code easy to update and manage over time. Constants help achieve that — but only if you organize and use them properly.

Best Practices for Maintainability:

  • Centralize constants:
    Define all your constants in a single configuration file (for example, config.php) instead of scattering them across multiple files.

    // config.php
    define("DB_HOST", "localhost");
    define("DB_USER", "root");
    define("DB_PASS", "password");
  • Use meaningful names:
    Names should describe the purpose of the constant clearly.

    define("MAX_LOGIN_ATTEMPTS", 5); // Good
    define("MLA", 5); // Poor
  • Group related constants together:
    You can organize related constants by naming convention or by placing them in the same file or class.

    class StatusCodes {
    const SUCCESS = 200;
    const NOT_FOUND = 404;
    const SERVER_ERROR = 500;
    }
  • Avoid redefining constants:
    Always check if a constant is defined before defining it again.

    if (!defined("SITE_URL")) {
    define("SITE_URL", "https://example.com");
    }

8.2 Security Considerations

Security is a key factor when using constants, especially if they store sensitive data such as API keys or database credentials.

Security Tips:

  • Never expose sensitive constants in public files.
    Keep them in configuration files outside the web root or use environment variables for better protection.

  • Use constants for fixed, non-user-editable values.
    Do not store user input or dynamic data in constants — their purpose is to remain unchanged.

  • Avoid printing sensitive constants.

    // Not recommended
    echo DB_PASS; // ❌ Exposes password
  • Restrict access when including configuration files.
    Use proper file permissions and avoid exposing configuration files directly through the browser.

Example of a safe setup:

/project-root/

├── public/ → accessible by web
│ └── index.php

└── config/ → outside web root
└── config.php (contains constants)

Then, in index.php:

require_once "../config/config.php";

8.3 Code Readability

Readable code is easier to understand and maintain, especially in large projects. Constants can help make code cleaner — but only if used consistently.

Readability Tips:

  • Use uppercase letters with underscores for constants (standard convention).

    const SITE_NAME = "MyWebsite";
  • Avoid unnecessary abbreviations.
    Use full, descriptive names for clarity.

    define("MAX_UPLOAD_SIZE_MB", 50);
  • Group constants logically in classes or namespaces.

    namespace App\Config;

    class Paths {
    const BASE = “/var/www/html/”;
    const LOGS = self::BASE . “logs/”;
    }

  • Comment complex constants.
    If a constant’s purpose isn’t immediately clear, add a short comment explaining it.

    define("TOKEN_EXPIRY_HOURS", 24); // Access token lifetime

Summary:

  • Keep constants organized, descriptive, and centralized.

  • Protect sensitive data by storing it securely.

  • Follow a consistent naming style for clarity and readability.

  • Remember: constants make your PHP application easier to maintain, more secure, and more understandable.

 

9. Summary

Constants in PHP are an essential feature that allow developers to define fixed values that cannot be changed during script execution. They improve code stability, readability, and maintainability by storing information that remains constant throughout a program — such as configuration settings, environment modes, or security-related values.

You can define constants in PHP using either define() or const:

  • define() is a function, used for defining constants at runtime.

  • const is a language construct, used for defining compile-time constants and for declaring class constants.

Constants are:

  • Global by default, meaning they can be accessed anywhere in the script.

  • Case-sensitive, unless explicitly set otherwise when using define().

  • Commonly named using uppercase letters and underscores for clarity and consistency.

PHP also provides several magic constants (like __FILE__, __LINE__, and __DIR__) that automatically return useful information about the script’s context — very helpful for debugging and managing file paths.

In real-world applications, constants are used for:

  • Configuration settings (e.g., database credentials, site URLs)

  • Environment control (e.g., development vs production modes)

  • Debugging and logging (e.g., defining log file paths or debug modes)

Key takeaways:

  • Use constants to store values that should never change.

  • Choose between define() and const based on context.

  • Follow clear naming conventions and secure configuration practices.

  • Leverage PHP’s built-in magic constants for efficient debugging and organization.

By using constants effectively, you make your PHP code cleaner, safer, and easier to manage.

Would you like me to add the “References and Further Reading” section next (with recommended PHP documentation and tutorials)?

Sure! Here’s a short, clear Summary for this topic:

9. Summary

Constants in PHP are fixed values that do not change during script execution. They are defined using either the define() function or the const keyword. Constants make your code more stable, readable, and maintainable, especially when storing configuration data or system settings.

Key points to remember:

  • Constants are global and can be accessed anywhere in your code.

  • They are case-sensitive by default.

  • Use uppercase names with underscores for clarity.

  • The const keyword is preferred inside classes, while define() is used for global constants.

  • Magic constants like __FILE__, __LINE__, and __DIR__ are built into PHP and provide useful runtime information.

By following best practices—using clear naming, secure configuration, and organized structure—constants help create PHP applications that are easier to debug, maintain, and scale.