PHP const vs define: What is the Difference?

In PHP, both the const keyword and the define() function are used to define constants, which are identifiers for simple values that cannot change during script execution. While they achieve similar results, they differ significantly in their execution timing, scope, flexibility, and performance. This article outlines the key differences between these two methods to help you understand when to use each in your PHP code.

Compile-Time vs. Run-Time Execution

The most fundamental difference between const and define() is how and when they are registered by the PHP engine:

// This is valid:
if (true) {
    define('STATUS', 'active');
}

// This will cause a syntax error:
if (true) {
    const STATUS = 'active'; 
}

Class Scope vs. Global Scope

Where you can declare and use these constants within your codebase also differs:

class User {
    // Valid:
    const ROLE = 'admin';
    
    // Invalid (will cause a syntax error):
    // define('ROLE', 'admin'); 
}

Dynamic Names

Sometimes you may need to generate the name of a constant dynamically.

$prefix = 'APP_';
define($prefix . 'VERSION', '1.0.0'); // Valid and works

// This is not possible with const:
// const $prefix . 'VERSION' = '1.0.0'; 

Performance

Because const is parsed at compile-time rather than run-time, it is slightly faster than define(), which carries the overhead of a function call. While this performance difference is negligible in small applications, using const is generally preferred for micro-optimizations in large-scale frameworks and libraries where many constants are declared.