PHP Constants
In this page:
Defining Constants with define()
define(SITE_NAME, 'Cookies & Cursor') creates a constant at runtime. Once set, a constant's value is locked for the rest of the script's execution — there's no reassignment operator for constants the way there is for variables, which is exactly the guarantee you want for values that must never change mid-script.
Example: Defining Constants with define()
<?php
define('SITE_NAME', 'Cookies & Cursor');
echo SITE_NAME;
?>
Login to try C/C++/Java/PHP code in the editor
The const Keyword
The const keyword defines a constant at compile time rather than runtime, which makes it slightly faster and is the standard way to declare constants inside a class. Outside a class, define() and const both work, but const requires the value to be a fixed literal rather than the result of a function call.
Example: The const Keyword
<?php
const MAX_USERS = 100;
echo MAX_USERS;
?>
Login to try C/C++/Java/PHP code in the editor
Constant Scope
Unlike a variable, a constant is automatically accessible everywhere in the script the moment it's defined — inside every function and every included file — without needing the global keyword. That global-by-default behavior is exactly why constants suit values like configuration settings or fixed limits.
Example: Constant Scope
<?php
define('APP_VERSION', '1.0');
function showVersion() {
echo APP_VERSION;
}
showVersion();
?>
Login to try C/C++/Java/PHP code in the editor
Magic Constants
PHP predefines several 'magic constants' — like __LINE__ and __FILE__ — whose value changes depending on where in your code they appear. __LINE__ always evaluates to the current line number, and __FILE__ to the full path of the file it's written in, which makes both genuinely useful for logging and debugging.
Example: Magic Constants
<?php
echo "Line: " . __LINE__ . "\n";
echo "File: " . __FILE__;
?>
Login to try C/C++/Java/PHP code in the editor
Constant Best Practices
Writing constant names in ALL_CAPS isn't enforced by PHP, but it's a near-universal convention that lets a reader instantly tell MAX_RETRIES is a fixed constant rather than a variable that might change. Grouping related constants together near the top of a file also makes configuration easy to find later.
Example: Constant Best Practices
<?php
define('MAX_RETRIES', 3);
define('MIN_RETRIES', 1);
echo MAX_RETRIES;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: