Constants
Reviewed & published by Brayan K
Some values should never change — a tax rate, a site name, an HTTP status code. Constants lock a value in place once and make it readable everywhere. This lesson covers const vs define(), array and class constants, and PHP's magic constants.
Part of the free PHP course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- Define constants with const and define()
- Know when each one is the right choice
- Store arrays in immutable constants
- Use class constants with the :: operator
- Read magic constants like __LINE__ and __FUNCTION__
- Understand global scope and naming conventions
1️⃣ Defining Constants
A constant is a named value that can never be reassigned. There's no $, and the convention is UPPER_CASE. You define one with const (modern) or define() (older). Unlike variables, constants are global — readable inside any function without the global keyword.
<?php
// A constant is a value fixed once and never changed.
// No $ sign, UPPER_CASE by convention.
const MAX_LOGIN_ATTEMPTS = 3; // modern, compile-time
define('SITE_NAME', 'LearnCoding'); // older, run-time function
echo MAX_LOGIN_ATTEMPTS . "\n"; // 3
echo SITE_NAME . "\n"; // LearnCoding
// Constants are GLOBAL: visible everywhere, even inside functions.
function greet() {
echo "Welcome to " . SITE_NAME . "\n"; // works without 'global'
}
greet();
// Trying to redefine is a fatal error:
// const MAX_LOGIN_ATTEMPTS = 5; // Error: cannot redefine
?>2️⃣ const vs define()
They look similar but differ in when they run. const is resolved at compile time and must sit at the top level with a literal name. define() is a function called at run time, so it can be conditional or build a name dynamically. Helpers defined() and constant() let you check for and fetch constants by name.
<?php
// const: parsed at COMPILE time, must be top-level, name is literal.
const TAX_RATE = 0.2;
// define(): runs at RUN time, so it can be conditional or dynamic.
if (!defined('ENVIRONMENT')) {
define('ENVIRONMENT', 'production');
}
// You can build a define() name dynamically — const cannot.
$key = 'FEATURE_' . strtoupper('beta');
define($key, true);
echo TAX_RATE . "\n"; // 0.2
echo ENVIRONMENT . "\n"; // production
var_dump(defined('FEATURE_BETA')); // bool(true)
var_dump(constant('FEATURE_BETA')); // bool(true) — fetch by name
?>3️⃣ Array Constants
Since PHP 7 a constant can hold an array, and it's fully immutable — perfect for fixed lookup tables, permission lists, or grouped configuration. You can read any element, but any attempt to modify it is a fatal error.
<?php
// Since PHP 7, constants can hold ARRAYS too.
const PERMISSIONS = ['read', 'write', 'delete'];
const CONFIG = [
'timeout' => 30,
'retries' => 3,
];
echo PERMISSIONS[1] . "\n"; // write
echo CONFIG['timeout'] . "\n"; // 30
echo count(PERMISSIONS) . "\n"; // 3
// The array is immutable — you can read it but not change it.
// PERMISSIONS[] = 'admin'; // Fatal error: cannot modify
?>4️⃣ Class Constants
Constants can also live inside a class, where they group related fixed values under a meaningful namespace. Declare them with const inside the class and access them with the :: operator (or self:: from within). Since PHP 7.1 they can carry visibility modifiers like public.
<?php
// CLASS constants belong to a class and use the :: operator.
class HttpStatus {
const OK = 200;
const NOT_FOUND = 404;
public const SERVER_ERROR = 500; // visibility allowed since PHP 7.1
}
echo HttpStatus::OK . "\n"; // 200
echo HttpStatus::NOT_FOUND . "\n"; // 404
// self:: refers to constants inside the same class.
class Circle {
const PI = 3.14159;
public function area(float $r): float {
return self::PI * $r ** 2;
}
}
echo (new Circle())->area(2) . "\n"; // 12.56636
?>5️⃣ Magic & Predefined Constants
Magic constants change value depending on where they appear — __LINE__, __FUNCTION__, __CLASS__, __FILE__ — and are invaluable for logging and debugging. PHP also ships predefined constants like PHP_VERSION, PHP_EOL, and PHP_INT_MAX.
<?php
// "Magic constants" change depending on WHERE they're used.
echo __LINE__ . "\n"; // 3 — the line this echo is written on
// PHP_VERSION is predefined too, but it prints whatever the server runs
// (8.4.19 here, something else on yours) — so test it instead of printing it.
echo (PHP_VERSION_ID >= 80000 ? "PHP 8 or newer" : "older than PHP 8") . "\n";
echo PHP_EOL === "\n" ? "unix newline\n" : "other\n";
function whoAmI() {
echo __FUNCTION__ . "\n"; // whoAmI — current function name
}
whoAmI();
echo PHP_INT_MAX . "\n"; // 9223372036854775807 on 64-bit
?>Now you try. Fill the ___ blanks to set up a small app config.
<?php
// 🎯 YOUR TURN — fill each ___ to set up app constants.
___ APP_VERSION = '2.1.0'; // 👉 use const
define(___, 'support@app.com'); // 👉 first arg: the name 'SUPPORT_EMAIL'
const LIMITS = ['daily' => ___]; // 👉 a number like 100
echo APP_VERSION . "\n"; // 2.1.0
echo SUPPORT_EMAIL . "\n"; // support@app.com
echo LIMITS['daily'] . "\n"; // 100
// ✅ Expected output:
// 2.1.0
// support@app.com
// 100
?>🧩 Reorder Challenge
These scrambled lines should define a rate, use it in a function, and print a result. Put them in the order that prints Tax: 4.
The constant RATE is defined first so the function can read it (constants are global, so no global keyword is needed). The function must be declared before it's called. 20 * 0.2 gives 4, so the output is Tax: 4.
🧠 Quick Recall
Predict the output before revealing each answer.
Prints 2. Array constants are allowed (since PHP 7) and you read elements by index just like any array — but you cannot modify them.
Prints no. defined() safely checks whether a constant exists without triggering an error.
Yes. Constants are global by nature, so a function can read SITE_NAME directly — no global keyword required, unlike with variables.
Common Errors (and the fix)
- "Cannot redefine constant" — you defined the same name twice. Constants are write-once; guard with if (!defined('NAME')) before a conditional define().
- You wrote $MAX instead of MAX — constants have no dollar sign. The $ makes it a (probably undefined) variable.
- "Undefined constant FOO" — in PHP 8 a bare unknown word is a fatal error, not a string. Quote your strings, and define constants before use.
- const fails inside an if-block — const must be top-level. Use define() for conditional definitions.
Pro Tips
- 💡 Default to const. It's clearer and compile-time; only use define() when you need run-time or dynamic names.
- 💡 Group related values as class constants. HttpStatus::OK reads far better than a loose HTTP_OK.
- 💡 Use magic constants in logs. __FILE__ and __LINE__ pinpoint exactly where a message came from.
📋 Quick Reference — Constants
| Syntax | Example | Notes |
|---|---|---|
| const | const MAX = 10; | Compile-time, top-level |
| define() | define('PI', 3.14) | Run-time, can be conditional |
| defined() | defined('PI') | Check existence |
| constant() | constant('PI') | Fetch by name |
| Class::CONST | HttpStatus::OK | Class constant access |
| __LINE__ | echo __LINE__ | Magic: current line |
| PHP_EOL | echo PHP_EOL | Predefined newline |
Mini-Challenge: Config & Discount
Write it yourself, run it on onecompiler.com/php or your own machine, then check against the expected output in the comments.
<?php
// 🎯 MINI-CHALLENGE: a tiny config + a discount calculation.
// No code filled in — follow the steps, then run and compare.
//
// 1. const CURRENCY = '$'.
// 2. const DISCOUNT_RATE = 0.15 (15% off).
// 3. $price = 80.00.
// 4. $saved = $price * DISCOUNT_RATE.
// 5. $final = $price - $saved.
// 6. echo two lines:
// You save: <CURRENCY><saved>
// Pay now: <CURRENCY><final>
// Use number_format(..., 2) on the amounts.
//
// ✅ Expected output:
// You save: $12.00
// Pay now: $68.00
// your code here
?>🎉 Lesson Complete!
- ✅ Constants have no $, are UPPER_CASE, and never change
- ✅ Prefer const; use define() for run-time or dynamic names
- ✅ Constants are global — readable inside any function
- ✅ Constants can hold immutable arrays; classes group them with ::
- ✅ Magic constants like __LINE__ aid logging and debugging
Practice quiz
Which character must a constant name NOT have?
- An underscore
- An uppercase letter
- A dollar sign $
- A digit
Answer: A dollar sign $. Constants have no dollar sign. Writing $MAX makes it a (probably undefined) variable instead.
What is the key difference between const and define()?
- const is compile-time and top-level; define() runs at run time and can be conditional/dynamic
- define() is faster
- const cannot hold strings
- They are identical
Answer: const is compile-time and top-level; define() runs at run time and can be conditional/dynamic. const is resolved at compile time and must be top-level with a literal name. define() is a run-time function, so it can be conditional or build a name dynamically.
Can a function read a top-level constant without the global keyword?
- No, it needs global
- Only if passed as an argument
- Only inside classes
- Yes — constants have global scope and are visible everywhere
Answer: Yes — constants have global scope and are visible everywhere. Constants are global by nature, so a function can read SITE_NAME directly with no global keyword, unlike variables.
What does this print? const C = [1, 2, 3]; echo C[1];
- 1
- 2
- 3
- Fatal error
Answer: 2. Array constants are allowed (since PHP 7) and you read elements by index, so C[1] is 2. You cannot, however, modify them.
Are constant arrays mutable?
- No — they are immutable; modifying one is a fatal error
- Yes, you can append with []
- Only class constant arrays are mutable
- Yes, but only the first element
Answer: No — they are immutable; modifying one is a fatal error. A constant array is fully immutable: you can read elements but any attempt to modify it is a fatal error.
How do you access a class constant such as OK on class HttpStatus?
- HttpStatus->OK
- HttpStatus.OK
- HttpStatus::OK
- $HttpStatus[OK]
Answer: HttpStatus::OK. Class constants are accessed with the :: operator: HttpStatus::OK.
What does echo defined('NOPE') ? 'yes' : 'no'; print when NOPE is undefined?
- yes
- no
- An error
- An empty string
Answer: no. defined() safely checks whether a constant exists without triggering an error, returning false here, so it prints no.
Which function fetches a constant's value by its name string?
- get_constant()
- value()
- fetch()
- constant()
Answer: constant(). constant('FEATURE_BETA') returns the value of the named constant; defined() checks whether it exists.
What is a magic constant like __LINE__?
- A constant that can be reassigned
- A special value that changes based on where it appears in code
- A class constant
- A user-defined constant
Answer: A special value that changes based on where it appears in code. Magic constants change value depending on where they are used — __LINE__ is the current line, __FUNCTION__ the current function name.
Why does defining const inside an if-block fail?
- if-blocks ban constants entirely
- You must use uppercase
- const must be top-level; use define() for conditional definitions
- Constants can't be booleans
Answer: const must be top-level; use define() for conditional definitions. const is compile-time and must sit at the top level. For a conditional or dynamic definition, use define().
Continue this course
- Previous: Type Juggling & Casting
- Next: Superglobals ($_GET, $_POST, $_SERVER) — Access request, server, and session data through PHP's built-in superglobals
- Quick reference: PHP cheat sheet
Frequently asked questions
What is the difference between const and define()?
Both create a constant — an unchangeable value with no dollar sign, written UPPER_CASE by convention. const is processed at compile time, must appear at the top level of a file or inside a class, and takes a literal name. define() is a function that runs at run time, so you can call it conditionally (inside an if) or build the constant name dynamically from a variable. For ordinary fixed values, const is the cleaner, preferred choice; reach for define() only when you genuinely need run-time or dynamic behaviour.
Are constants global? Can I use them inside functions?
Yes. Unlike variables, constants have global scope and are visible everywhere once defined — including inside functions and classes — without any global keyword. That's part of what makes them ideal for configuration values like a site name, a tax rate, or an API base URL that the whole application needs to read.
Can a PHP constant hold an array?
Yes, since PHP 7 a constant can hold an array, and the array is immutable: you can read elements like CONFIG['timeout'] but you cannot add to or modify it. This makes constant arrays a neat way to store fixed lookup tables, permission lists, or grouped configuration. Class constants can hold arrays too, accessed with the :: operator.
What are class constants and magic constants?
Class constants belong to a class, are declared with const inside it, and are accessed with the :: operator — for example HttpStatus::OK. Since PHP 7.1 they can have visibility modifiers (public/protected/private). Magic constants are special predefined values that change based on where they appear: __LINE__ is the current line, __FUNCTION__ the current function name, __CLASS__ the class name, and __FILE__ the file path. PHP also ships predefined constants like PHP_VERSION, PHP_EOL, and PHP_INT_MAX.