PHP Constants: define() vs const & Built-In Magic Constants

Unlike variables whose contents can be modified at any point in your script, a constant is an identifier holding a value that remains immutable throughout the entire script execution lifecycle. Constants are ideal for application configuration settings that should never be altered accidentally—such as database hostnames, encryption keys, tax rates, and file directory paths.

Key Characteristics of PHP Constants

  • Constants do NOT have a leading dollar sign ($).
  • By convention, constant names are written in UPPERCASE_WITH_UNDERSCORES.
  • Constants have global scope automatically across all functions, classes, and include files.
  • Once assigned, a constant cannot be redefined or cleared with unset().

Method 1: Creating Constants with define()

The define() function creates a constant at runtime. It takes the constant name and its value as parameters:

<?php
    // Syntax: define(name, value);
    define("SITE_NAME", "Veewom Educational Hub");
    define("DATABASE_HOST", "localhost");
    define("APP_VERSION", 8.2);

    echo "Welcome to " . SITE_NAME . " (v" . APP_VERSION . ")<br>";

    // Constants containing Arrays (PHP 7+)
    define("SUPPORTED_ROLES", ["admin", "editor", "student"]);
    echo "Default role: " . SUPPORTED_ROLES[2];
?>

Method 2: Creating Constants with the const Keyword

The const keyword creates constants at compile time. It is cleaner, faster, and is the standard syntax for defining constants inside Object-Oriented classes:

<?php
    const MAX_LOGIN_ATTEMPTS = 5;
    const DEFAULT_TIMEZONE = "Asia/Kolkata";

    echo "Allowed Login Attempts: " . MAX_LOGIN_ATTEMPTS . "<br>";

    // Used inside Object-Oriented Classes
    class ServerConfig {
        public const PORT = 8080;
        public const SSL_ENABLED = true;
    }

    echo "Server Port: " . ServerConfig::PORT;
?>

Technical Comparison: define() vs const

Comparison Factor define() Function const Keyword
Execution Timing Evaluated at Runtime. Evaluated at Compile time (faster).
Conditional Blocks Can be placed inside if (...) { define(...); } blocks. Cannot be placed inside control statements or functions.
OOP Class Constants Cannot be used inside class definitions. The standard way to declare class constants (public const ...).

PHP Magic Constants: Dynamic Pre-Defined Constants

PHP includes 9 special predefined constants known as Magic Constants. Unlike regular constants, magic constants change dynamically depending on where they are called in source code:

Magic Constant Value Returned at Runtime Practical Development Usage
__LINE__ The current line number in the source file. Error logging and debugging trace points.
__FILE__ The full absolute filesystem path of the current file. Troubleshooting file system paths.
__DIR__ The directory of the current file (equivalent to dirname(__FILE__)). Bulletproof file includes: require_once __DIR__ . '/config.php';
__FUNCTION__ The current active function name. Automated logging in backend service methods.
__CLASS__ The current active class name (OOP). Reflection, design patterns, and factory methods.
__METHOD__ The class and method name (e.g. User::getProfile). Audit logs and performance tracing.
__NAMESPACE__ The current namespace identifier. PSR-4 autoloading routing.
<?php
    echo "Current File Path: " . __FILE__ . "<br>";
    echo "Current Directory: " . __DIR__ . "<br>";
    echo "This code is executing on Line: " . __LINE__ . "<br>";

    function debugLogger() {
        echo "Executing inside function: " . __FUNCTION__ . "<br>";
    }
    debugLogger();
?>

BCA / CS University Exam Corner

High-Frequency Viva Question:

Q: How do you check if a constant is already defined before creating it?
A: Use the built-in defined() function:
if (!defined('DB_NAME')) { define('DB_NAME', 'veewom_db'); }.

Interactive Student Practice Session

Exercise 8.1: Create an application configuration file defining constants for DB_HOST, DB_USER, DB_PASS, and DB_NAME. Access them inside a test function to prove global scope.

Exercise 8.2: Write a script that uses __DIR__ to safely include a file located in an includes/ subfolder.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!