Skip to content

PHP Constants


Constants are like variables, but they cannot be changed once they are defined.

  • In PHP, you can define constants using the define() function or the const keyword.
  • A constant can be defined with various data types.

// String constants
define('SITE_NAME', 'My Website');
define('DATABASE_HOST', 'localhost');
// Integer constants
define('MAX_USERS', 1000);
define('DEFAULT_PORT', 3306);
// Float constants
define('PI', 3.14159);
define('TAX_RATE', 0.085);
// Boolean constants
define('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 constant
define('DEFAULT_AVATAR', null);

// String constants
const SITE_NAME = 'My Website';
const DATABASE_HOST = 'localhost';
// Integer constants
const MAX_USERS = 1000;
const DEFAULT_PORT = 3306;
// Float constants
const PI = 3.14159;
const TAX_RATE = 0.085;
// Boolean constants
const 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 constant
const DEFAULT_AVATAR = null;

  1. 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.
  2. const keyword:

    • 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.

if (defined("CONSTANT_NAME")) {
echo "CONSTANT_NAME is defined";
} else {
echo "CONSTANT_NAME is not defined";
}
echo CONSTANT_NAME;

// String
echo SITE_NAME; // Outputs: My Website
// Integer
echo MAX_USERS; // Outputs: 1000
// Float
echo PI; // Outputs: 3.14159
// Boolean
var_dump(DEBUG_MODE); // Outputs: bool(true)
// Array
print_r(ALLOWED_EXTENSIONS);
// Outputs: Array ( [0] => jpg [1] => png [2] => gif [3] => pdf )
// Accessing array elements
echo ALLOWED_EXTENSIONS[0]; // Outputs: jpg
echo DATABASE_CONFIG['host']; // Outputs: localhost
// Null
var_dump(DEFAULT_AVATAR); // Outputs: NULL

Class constants with different data types:

Section titled “Class constants with different data types:”
AppConfig.php
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.0
echo AppConfig::MAX_FILE_SIZE; // Outputs: 5242880
var_dump(AppConfig::CACHE_ENABLED); // Outputs: bool(true)
print_r(AppConfig::SUPPORTED_FORMATS); // Outputs array

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.

Returns the current line number of the file.

echo "This is line number: " . __LINE__; // Outputs: This is line number: 2
echo "This is line number: " . __LINE__; // Outputs: This is line number: 3

Returns the full path and filename of the current file (with symlinks resolved).

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

Returns the directory of the current file (equivalent to dirname(__FILE__)).

echo __DIR__; // Outputs: /var/www/html
include __DIR__ . '/config.php'; // Include file from same directory

Returns the name of the current function (case-sensitive as declared).

function getUserData() {
echo "Currently in function: " . __FUNCTION__; // Outputs: getUserData
}
getUserData();

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();

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();

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
}
}

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");

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);
}
// Usage
logError("Database connection failed");

// Include configuration file from same directory
require_once __DIR__ . '/config.php';
// Include class file based on current namespace
$classFile = __DIR__ . '/' . str_replace('\\', '/', __NAMESPACE__) . '/' . __CLASS__ . '.php';

class DebugHelper {
public static function getDebugInfo() {
return [
'file' => __FILE__,
'line' => __LINE__,
'class' => __CLASS__,
'method' => __METHOD__,
'namespace' => __NAMESPACE__,
'directory' => __DIR__
];
}
}
// Usage
print_r(DebugHelper::getDebugInfo());

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');