Constants
Pageturn charges 20% VAT on every sale, and the shop's name appears on every page. If those values live in ordinary variables, one careless $vat = 0; deep in a template can change the price of everything. Values that must never change belong in constants.
The rule
A constant is set once, has no
$, and is visible everywhere.
Two ways to create one:
<?php
const VAT_RATE = 0.20; // at the top level of a file (or in a class)
define("SHOP_NAME", "Pageturn"); // a function call; works anywhere
function withVat(float $price): float {
return $price * (1 + VAT_RATE); // no global needed
}
echo SHOP_NAME; // Pageturn
echo withVat(10); // 12The key properties:
- No dollar sign. You write
VAT_RATE, not$VAT_RATE. By convention names are UPPER_SNAKE_CASE. - Set once. A second
define("SHOP_NAME", ...)does not change the value; PHP issues a warning ("already defined") and keeps the original. Assigning with=is not possible at all. - Global visibility. Unlike variables, constants can be read inside any function without passing them in. That is safe precisely because nobody can change them.
- Case-sensitive.
VAT_RATEandvat_rateare different names.
const or define? const is checked when the file is compiled, so it must sit at the top level (or inside a class), never inside an if or a function. define() runs like any other call, so it can be used conditionally, for example after reading a configuration file. Prefer const for fixed values.
PHP also ships built-in constants you will use often: PHP_EOL (the line ending), PHP_INT_MAX (the largest integer), PHP_VERSION. And there are "magic" constants whose value depends on where they appear, such as __LINE__ (the current line number) and __DIR__ (the folder of the current file).
The shortcut
For every value, ask "should anything ever be allowed to change this while the script runs?" If not, make it a constant.
VAT rate
Fixed by law for the whole request. Constant:
const VAT_RATE = 0.20;
Drills
Answer fast — trust the rule.
How do you read a constant named VAT_RATE?
What happens when a script calls define("SHOP_NAME", "Other") after SHOP_NAME is already defined?
Which way of creating a constant can appear inside an if block?
Which value should be a constant rather than a variable?
Remember
- A constant is set once, has no
$, and is visible everywhere. - Shortcut: "should anything change this while the script runs?" No → constant.
- Trap:
constcannot go inside anifor a function; usedefine()there.
