Constants are identifiers for simple values that cannot be altered or undefined during script execution. Unlike variables, constants do not start with a dollar sign $, are globally accessible throughout script execution, and are defined using either const or define().
const vs define()| Feature | const |
define() |
|---|---|---|
| Execution Timing | Defined at compile-time | Defined at run-time |
| Placement Context | Allowed in global scope, class definitions, & interfaces | Allowed anywhere, including inside conditionals |
| Case Insensitivity | Never allowed | Allowed in legacy PHP (Deprecated in 7.3+) |
| Expression Support | Scalar expressions supported | Full dynamic evaluation supported |
PHP provides 8 magic constants that change dynamically based on where they are used:
__LINE__: Current line number in file.__FILE__: Full path and filename of current file.__DIR__: Directory path of current file.__FUNCTION__: Current function name.__CLASS__: Current class name including namespace.__METHOD__: Current class method name.__NAMESPACE__: Current namespace name.flowchart TD
A["Constants Definition"] --> B["Global / Scope Constants"]
A --> C["Magic Constants"]
B --> B1["const API_KEY = 'xyz'"]
B --> B2["define('APP_ENV', 'production')"]
C --> C1["__DIR__ (File Directory Path)"]
C --> C2["__FILE__ (Absolute File Path)"]
C --> C3["__CLASS__ / __METHOD__"]
<?php
declare(strict_types=1);
namespace App\Config;
// Compile-time Constant
const MAX_UPLOAD_LIMIT_MB = 25;
// Runtime Constant Definition
define('APP_START_TIMESTAMP', microtime(true));
class Environment
{
public const STAGING_URL = "https://staging.kodersolution.com";
public function debugInfo(): array
{
return [
'file' => __FILE__,
'directory' => __DIR__,
'class' => __CLASS__,
'method' => __METHOD__,
'line' => __LINE__,
];
}
}
$env = new Environment();
echo "Max Upload Limit: " . MAX_UPLOAD_LIMIT_MB . " MB
";
echo "Staging URL: " . Environment::STAGING_URL . "
";
echo "Current File Directory: " . __DIR__ . "
";
const over define() for Hardcoded Configuration: const is cleaner, faster, and works natively inside classes and interfaces.__DIR__ for Autoloading & Includes: Use require_once __DIR__ . '/../vendor/autoload.php'; instead of fragile relative file paths.DEFAULT_TIMEZONE).Write a PHP class DatabaseConfig with a public const DB_PORT = 3306; and a method getConfigFile() that returns __DIR__ . '/config.json'!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.