In this chapter
We'll learn how to give fixed values like prices and opening hours a name that can never change — with const and define() — why a mistyped constant stops PHP instead of printing a blank, and the built-in and "magic" constants PHP gives you for free.
The Problem in Real Life
Tom is raising the haircut price from £25 to £28. Mia searches booking.php for 25. It appears six times: four are the price, one is a 25-minute break, and one is part of a date. She changes four, nervously.
Then Olivia forwards an email from a customer: "Thanks for the free haircut!" For one hour yesterday, every booking was charged £0. Halfway down the file, Mia finds a line she added while testing and forgot: $haircutPrice = 0;. Everything below it used the new value.
"Some values should be set once and never change while the code runs," says Marcus. "Not by a test line, not by you, not by anyone. PHP has exactly that."
How do I make a value that nobody — not even me, by accident — can change?
Mia
A Number Typed Everywhere vs. a Name Set Once
The same number everywhere
A price typed six times means six places to update — and six chances to miss one.
Values that shouldn't change
A variable can be overwritten by any later line, even a forgotten test.
What does 25 mean?
A bare 25 could be a price, minutes or a date. The code doesn't say which.
Constants and Magic Constants
Constants: a constant is a name for a value that is set once and can never change while the file runs. Use one for values that are fixed for the whole program: the shop's name, opening hours, prices, how many slots fit in an hour. Compared with a variable, a constant:
- Has no dollar sign:
HAIRCUT_PRICE, not$HAIRCUT_PRICE. - Is written in UPPER_SNAKE_CASE: by convention (Act 02, chapter 4), so you can spot one at a glance.
- Can't be changed or set twice: once it has a value, the value stays until the file finishes.
- Can be used everywhere: anywhere in the file, and inside functions too — unlike variables, as chapter 5 shows.
- Stops the file if you mistype it: a misspelled constant is a fatal error, not a quiet warning.
Defining a constant with const: the usual way is the const keyword: const HAIRCUT_PRICE = 25;. The code below defines some of the shop's fixed values and uses them. The value can be a number, text, true or false, null, or a list — and it can even be a calculation, as long as PHP can work it out from fixed values and other constants, like OPENING_HOUR + 9. Now Tom's price lives in exactly one place: change it there, and every use follows. A bare number like 25 scattered through code is often called a magic number, because nobody can tell what it means — a named constant fixes that too.
<?phpconst SHOP_NAME = "Tom's Barbershop";const HAIRCUT_PRICE = 25;const OPENING_HOUR = 9;const CLOSING_HOUR = OPENING_HOUR + 9; // worked out from another constant: 18const SERVICES = ["Haircut", "Beard trim"]; // a list (Act 08)echo SHOP_NAME, " is open from ", OPENING_HOUR, ":00 to ", CLOSING_HOUR, ":00\n";echo "A haircut costs £", HAIRCUT_PRICE, "\n";echo "Second service: ", SERVICES[1], "\n";
Output: Tom's Barbershop is open from 9:00 to 18:00, then A haircut costs £25, then Second service: Beard trim.
Constants aren't filled in inside quotes: in double quotes, PHP replaces $variables with their values (Act 02, chapter 5), but it does not do this for constants. "£HAIRCUT_PRICE" prints the word HAIRCUT_PRICE itself. Print constants with commas in echo, or join them with the dot, as below.
<?phpconst HAIRCUT_PRICE = 25;echo "Price: £HAIRCUT_PRICE\n"; // Price: £HAIRCUT_PRICE (not filled in)echo "Price: £", HAIRCUT_PRICE, "\n"; // Price: £25echo "Price: £" . HAIRCUT_PRICE . "\n"; // Price: £25
Constants can't change: that's the whole point. Assigning a new value with = is a parse error, so PHP won't even run the file. Defining the same constant a second time doesn't change it either: PHP keeps the first value and warns Constant HAIRCUT_PRICE already defined — and the message itself says this will become a full error in PHP 9. A forgotten test line can never quietly change a price again.
<?phpconst SHOP_NAME = "Tom's Barbershop";SHOP_NAME = "Bob's Barbershop";// Parse error: syntax error, unexpected token "=" in main.php on line 4
<?phpconst HAIRCUT_PRICE = 25;const HAIRCUT_PRICE = 0; // the forgotten test lineecho HAIRCUT_PRICE; // 25// Warning: Constant HAIRCUT_PRICE already defined, this will be an error in PHP 9
const only at the top level: PHP reads const lines before it starts running the file. So const can only be used at the top level of a file (and inside classes, which you'll meet in Act 11) — not inside an if block, a loop or a function. If you try, you get a parse error, as below.
<?phpif (true) {const BOOKING_FEE = 2;}// Parse error: syntax error, unexpected token "const" in main.php on line 4
define(): the other way to create a constant is the define() function: define("BOOKING_FEE", 2);. Notice that the name is given as text, in quotes. Because define() is a normal function that runs when PHP reaches it, it can be used inside an if — for example, to choose a value depending on a setting. To check whether a constant exists, use defined("BOOKING_FEE"), which gives true or false. In everyday code, prefer const: it's shorter and clearer. Use define() only when a constant must be created conditionally.
<?php$mode = "test";if ($mode === "test") { // === means "is exactly equal to" (Act 05)define("BOOKING_FEE", 0); // no fee while testing} else {define("BOOKING_FEE", 2);}echo "Booking fee: £", BOOKING_FEE, "\n"; // Booking fee: £0var_dump(defined("BOOKING_FEE")); // bool(true)var_dump(defined("DEPOSIT")); // bool(false)
A typo in a constant stops the file: here's the big difference from chapter 1. A misspelled variable gives a warning and an empty value. A misspelled constant is a fatal error — Undefined constant — and PHP stops right there. That sounds worse, but it's much better: the mistake can't hide, so you find it the first time you run the file — not when Olivia finds a blank on the live site. One more reason to put fixed values in constants. Remember that constant names are case-sensitive too.
<?phpconst HAIRCUT_PRICE = 25;echo HAIRCUT_PRCE;echo "This line never runs";
Fatal error: Uncaught Error: Undefined constant "HAIRCUT_PRCE" in main.php:4
The file stops at line 4. Compare chapter 1: a misspelled variable only warned and carried on.
Global and built-in constants: a constant you define at the top level of a file is a global constant: from then on it can be used anywhere — further down the file, inside functions, and in other files loaded later (Act 10). In the code below, the function uses BOOKING_FEE without any extra work. PHP also comes with many built-in constants that are always there. The table lists a few you'll meet soon.
| Constant | What it holds | Example value |
|---|---|---|
| PHP_VERSION | The version of PHP that is running | 8.5.2 |
| PHP_EOL | The line-break character(s) for this system | \n on Linux and macOS |
| PHP_INT_MAX | The largest whole number PHP can hold | 9223372036854775807 |
| E_ALL | "Report every kind of error" (Act 01's php.ini) | used in error_reporting |
| M_PI | The number pi | 3.1415926535898 |
<?phpconst BOOKING_FEE = 2;function priceWithFee(int $price): int{return $price + BOOKING_FEE; // constants work inside functions}echo priceWithFee(25), PHP_EOL; // 27echo "Running on PHP ", PHP_VERSION, PHP_EOL;
PHP_EOL is a line break, just like "\n" on Linux and macOS.
Magic constants: finally, PHP has a few special constants that change depending on where you use them. They start and end with two underscores, and PHP fills them in for you: __LINE__ is the current line number, __FILE__ the full path of the current file, __DIR__ the folder that file is in, and __FUNCTION__ the name of the function you're inside. Three more — __CLASS__, __METHOD__ and __NAMESPACE__ — belong to classes (Act 11) and namespaces (Act 13). You'll use __DIR__ a lot in Act 10, to load other files by a path that always works. They're mostly useful for messages and logs that say exactly where something happened.
| Magic constant | Gives you | Example |
|---|---|---|
| __LINE__ | The current line number | 12 |
| __FILE__ | The full path of this file | /var/www/bookbay/booking.php |
| __DIR__ | The folder this file is in | /var/www/bookbay |
| __FUNCTION__ | The name of the current function | priceWithFee |
| __CLASS__, __METHOD__ | The current class and method (Act 11) | Booking, Booking::save |
| __NAMESPACE__ | The current namespace (Act 13) | BookBay\Pricing |
<?phpecho "This is line ", __LINE__, "\n"; // This is line 3echo "File: ", __FILE__, "\n";echo "Folder: ", __DIR__, "\n";function showSlots(): void{echo "Inside: ", __FUNCTION__, "\n"; // Inside: showSlots}showSlots();
On a server, File and Folder show real paths like /var/www/bookbay/booking.php. In the Playground the file is called main.php and the folder is /.
Choosing between a constant and a variable: ask one question — can this value change while the program runs? The shop's name, prices, opening hours and the length of a slot are fixed: constants. Today's bookings, the customer's name and the current time are different on every run: variables. (Values that differ between your laptop and the live server, like a database password, go into configuration instead — you'll see how later in the course.)
Key Takeaway
A constant is a name for a value that is set once and never changes: no $, UPPER_SNAKE_CASE, usable everywhere, including inside functions. Create it with const at the top level (the usual way) or define() when it must be conditional. A misspelled constant is a fatal error, so it can't hide like a misspelled variable. Magic constants like __LINE__ and __DIR__ depend on where they're written.
Why This Matters
Fixed values written once, with a clear name, are how BookBay will change a price in one line instead of hunting through files — and how a test line can never again make every haircut free. A name like HAIRCUT_PRICE also tells the next reader what a number means, where 25 tells them nothing.
Constants also show a pattern you'll meet again and again: PHP being strict is good for you. A misspelled constant stops the file at once; a misspelled variable hides. Later Acts — types, strict comparisons, PHPStan — all push your code in the same direction: mistakes should be loud.
Tom's prices, the opening hours and the slot length now live in constants at the top of the file, each written exactly once. While reviewing the change, Marcus opens the freelancer's old report.php and points at a line: $$field = $value;. "Two dollar signs," says Mia. "Is that a typo too?" It isn't — and it leads to one of PHP's stranger ideas. That's the next chapter.
