PHP Constants
Constants are like variables, but they cannot be changed once they are defined.
How to define a constant?
Section titled “How to define a constant?”- In PHP, you can define constants using the define()function or theconstkeyword.
- A constant can be defined with various data types.
1. Using the define() function
Section titled “1. Using the define() function”// String constantsdefine('SITE_NAME', 'My Website');define('DATABASE_HOST', 'localhost');
// Integer constantsdefine('MAX_USERS', 1000);define('DEFAULT_PORT', 3306);
// Float constantsdefine('PI', 3.14159);define('TAX_RATE', 0.085);
// Boolean constantsdefine('DEBUG_MODE', true);define('MAINTENANCE_MODE', false);
// Array constants (PHP 7.0+)define('ALLOWED_EXTENSIONS', ['jpg', 'png', 'gif', 'pdf']);define('DATABASE_CONFIG', [    'host' => 'localhost',    'port' => 3306,    'name' => 'myapp']);
// Null constantdefine('DEFAULT_AVATAR', null);2. Using the const keyword (PHP 5.3+)
Section titled “2. Using the const keyword (PHP 5.3+)”// String constantsconst SITE_NAME = 'My Website';const DATABASE_HOST = 'localhost';
// Integer constantsconst MAX_USERS = 1000;const DEFAULT_PORT = 3306;
// Float constantsconst PI = 3.14159;const TAX_RATE = 0.085;
// Boolean constantsconst DEBUG_MODE = true;const MAINTENANCE_MODE = false;
// Array constants (PHP 5.6+)const ALLOWED_EXTENSIONS = ['jpg', 'png', 'gif', 'pdf'];const DATABASE_CONFIG = [    'host' => 'localhost',    'port' => 3306,    'name' => 'myapp'];
// Null constantconst DEFAULT_AVATAR = null;Key differences
Section titled “Key differences”- 
define()function:- Can be used anywhere in your code (including inside functions, conditionals, etc.),
- Can use variables or expressions for the constant name,
- Works with all PHP versions,
- Array constants supported since PHP 7.0.
 
- 
constkeyword:- Must be declared at the top level of the script (not inside functions or classes, except for class constants),
- The constant name must be a literal string,
- Only available in PHP 5.3 and later,
- Slightly faster performance,
- Array constants supported since PHP 5.6.
 
Checking if a constant is defined
Section titled “Checking if a constant is defined”if (defined("CONSTANT_NAME")) {    echo "CONSTANT_NAME is defined";} else {    echo "CONSTANT_NAME is not defined";}Accessing a constant
Section titled “Accessing a constant”echo CONSTANT_NAME;Example usage:
Section titled “Example usage:”// Stringecho SITE_NAME;  // Outputs: My Website
// Integerecho MAX_USERS;  // Outputs: 1000
// Floatecho PI;         // Outputs: 3.14159
// Booleanvar_dump(DEBUG_MODE);  // Outputs: bool(true)
// Arrayprint_r(ALLOWED_EXTENSIONS);// Outputs: Array ( [0] => jpg [1] => png [2] => gif [3] => pdf )
// Accessing array elementsecho ALLOWED_EXTENSIONS[0];  // Outputs: jpgecho DATABASE_CONFIG['host']; // Outputs: localhost
// Nullvar_dump(DEFAULT_AVATAR);    // Outputs: NULLClass constants with different data types:
Section titled “Class constants with different data types:”class AppConfig {    const VERSION = '2.1.0';              // String    const MAX_FILE_SIZE = 5242880;         // Integer (5MB in bytes)    const UPLOAD_RATE_LIMIT = 10.5;        // Float    const CACHE_ENABLED = true;            // Boolean    const SUPPORTED_FORMATS = ['json', 'xml', 'csv']; // Array    const DEFAULT_THEME = null;            // Null}
echo AppConfig::VERSION;                   // Outputs: 2.1.0echo AppConfig::MAX_FILE_SIZE;             // Outputs: 5242880var_dump(AppConfig::CACHE_ENABLED);        // Outputs: bool(true)print_r(AppConfig::SUPPORTED_FORMATS);     // Outputs arrayMagic Constants
Section titled “Magic Constants”Magic constants are predefined constants in PHP that provide contextual information about the script and its execution environment. They are automatically defined by PHP and change their value depending on where they are used in the code.
Magic constants start and end with double underscores (__) and are case-insensitive. Their values are resolved at compile time, not runtime.
Available Magic Constants
Section titled “Available Magic Constants”__LINE__
Section titled “__LINE__”Returns the current line number of the file.
echo "This is line number: " . __LINE__;  // Outputs: This is line number: 2echo "This is line number: " . __LINE__;  // Outputs: This is line number: 3__FILE__
Section titled “__FILE__”Returns the full path and filename of the current file (with symlinks resolved).
echo __FILE__;  // Outputs: /var/www/html/index.phpecho basename(__FILE__);  // Outputs: index.php__DIR__
Section titled “__DIR__”Returns the directory of the current file (equivalent to dirname(__FILE__)).
echo __DIR__;  // Outputs: /var/www/htmlinclude __DIR__ . '/config.php';  // Include file from same directory__FUNCTION__
Section titled “__FUNCTION__”Returns the name of the current function (case-sensitive as declared).
function getUserData() {    echo "Currently in function: " . __FUNCTION__;  // Outputs: getUserData}
getUserData();__CLASS__
Section titled “__CLASS__”Returns the name of the current class (case-sensitive as declared).
class UserManager {    public function showClassName() {        echo "Current class: " . __CLASS__;  // Outputs: UserManager    }}
$user = new UserManager();$user->showClassName();__METHOD__
Section titled “__METHOD__”Returns the class method name (includes class name and method name).
class DatabaseConnection {    public function connect() {        echo "Current method: " . __METHOD__;  // Outputs: DatabaseConnection::connect    }
    private static function getConfig() {        echo "Current method: " . __METHOD__;  // Outputs: DatabaseConnection::getConfig    }}
$db = new DatabaseConnection();$db->connect();__NAMESPACE__
Section titled “__NAMESPACE__”Returns the name of the current namespace.
namespace App\Controllers;
class HomeController {    public function index() {        echo "Current namespace: " . __NAMESPACE__;  // Outputs: App\Controllers        echo "Full class name: " . __NAMESPACE__ . '\\' . __CLASS__;  // App\Controllers\HomeController    }}__TRAIT__
Section titled “__TRAIT__”Returns the trait name (case-sensitive as declared).
trait Loggable {    public function log($message) {        echo "Logging from trait: " . __TRAIT__ . " - " . $message;  // Outputs: Loggable    }}
class User {    use Loggable;}
$user = new User();$user->log("User created");Practical Examples
Section titled “Practical Examples”Error Logging with Context
Section titled “Error Logging with Context”function logError($message) {    $logEntry = sprintf(        "[%s] Error in %s on line %d: %s\n",        date('Y-m-d H:i:s'),        __FILE__,        __LINE__,        $message    );    error_log($logEntry);}
// UsagelogError("Database connection failed");Dynamic File Inclusion
Section titled “Dynamic File Inclusion”// Include configuration file from same directoryrequire_once __DIR__ . '/config.php';
// Include class file based on current namespace$classFile = __DIR__ . '/' . str_replace('\\', '/', __NAMESPACE__) . '/' . __CLASS__ . '.php';Debug Information
Section titled “Debug Information”class DebugHelper {    public static function getDebugInfo() {        return [            'file' => __FILE__,            'line' => __LINE__,            'class' => __CLASS__,            'method' => __METHOD__,            'namespace' => __NAMESPACE__,            'directory' => __DIR__        ];    }}
// Usageprint_r(DebugHelper::getDebugInfo());Automatic Class Loading
Section titled “Automatic Class Loading”function autoloader($className) {    $file = __DIR__ . '/classes/' . str_replace('\\', '/', $className) . '.php';    if (file_exists($file)) {        require_once $file;        echo "Loaded class from: " . $file . " (detected from " . __FILE__ . ")\n";    }}
spl_autoload_register('autoloader');