Skip to content

PHP Constants

Constants are like variables, but their value cannot be changed once defined. They’re useful for values that should remain fixed throughout your application, like configuration settings.

define('SITE_NAME', 'My Website');
echo SITE_NAME; // My Website
// SITE_NAME = 'Other'; // Error: cannot reassign a constant

Works anywhere in your code, including inside functions and conditionals.

define('MAX_USERS', 1000);
define('TAX_RATE', 0.085);
define('DEBUG_MODE', true);
define('ALLOWED_TYPES', ['jpg', 'png', 'gif']);

Must be declared at the top level of a script or inside a class. Slightly faster performance.

const MAX_USERS = 1000;
const TAX_RATE = 0.085;
const DEBUG_MODE = true;
const ALLOWED_TYPES = ['jpg', 'png', 'gif'];
Featuredefine()const
LocationAnywhere (functions, conditionals)Top level or class only
NameCan use variablesMust be literal string
SpeedSlightly slowerSlightly faster

// Check if defined
if (defined('MAX_USERS')) {
echo MAX_USERS;
}
// Access array constant elements
echo ALLOWED_TYPES[0]; // jpg

Constants can be defined inside classes and accessed with ::.

class AppConfig {
const VERSION = '2.1.0';
const MAX_FILE_SIZE = 5242880;
const SUPPORTED_FORMATS = ['json', 'xml', 'csv'];
}
echo AppConfig::VERSION; // 2.1.0
echo AppConfig::SUPPORTED_FORMATS[0]; // json

Magic constants are predefined by PHP and provide information about the current script. They start and end with double underscores and their values change based on where they’re used.

Current line number.

echo __LINE__; // 5

Full path and filename.

echo __FILE__; // /var/www/html/index.php
echo basename(__FILE__); // index.php

Directory of the current file.

echo __DIR__; // /var/www/html
include __DIR__ . '/config.php';

Current function name.

function process() {
echo __FUNCTION__; // process
}

Current class name.

class User {
public function getName() {
echo __CLASS__; // User
}
}

Current class and method name.

class User {
public function save() {
echo __METHOD__; // User::save
}
}

Current namespace.

namespace App\Controllers;
echo __NAMESPACE__; // App\Controllers

Current trait name.

trait Loggable {
public function log() {
echo __TRAIT__; // Loggable
}
}

Magic constants are useful for debugging and logging:

function logError($message) {
$entry = sprintf(
"[%s] %s:%d - %s",
date('Y-m-d H:i:s'),
__FILE__,
__LINE__,
$message
);
error_log($entry);
}