The Analogy: The Gauge Room At The Machine Works
At the back of a machine works, behind a door that stays shut, there is a small room kept at twenty degrees all year round. Along one wall is a felt-lined wooden case holding a set of slip gauges: rectangular blocks of hardened steel, each one ground to a thickness certified to a tenth of a micron. Nobody makes anything in this room. The blocks exist so that every other measuring instrument in the building can be checked against them, and their whole value lies in the fact that they are never adjusted, never carried out onto the floor, and never used to do work. A gauge that has been touched is a gauge that has to be recertified.
The room holds two quite different kinds of standard, and the works treats them differently. The slip gauges themselves were cut at the makers and sealed in the case before the works ever took delivery; their sizes were fixed at manufacture and nothing that happens on this site can alter them. Beside the case, screwed to the wall, is a slate on which the foreman has chalked the figures that apply to this particular shop: the reference temperature, the shift the inspector works, the bay the current batch came from. Those are just as binding as the slip gauges once the day starts -- nobody argues with the slate -- but they were written here, this morning, by somebody who had to look at a thermometer first.
Everything that leaves the room carries a mark saying where it came from. The inspector's stamp goes on the certificate, the bench number on the docket, the line of the day book where the reading was written. None of those figures is something the inspector chose. They are recorded automatically by the act of doing the work, and their whole purpose is that six months later, when a customer disputes a part, somebody can walk back from the certificate to the exact bench, the exact inspector and the exact line in the book.
The failure mode is quiet and it is always the same. Somebody needs a 3 mm block on the floor and the gauge room is locked, so a second, unofficial set appears in a drawer by the lathe -- same nominal sizes, same box, no certificate. For months every part measures correctly, because the two sets agree closely enough for the work in hand. Then the drawer set gets dropped, or lapped, or simply wears, and now the shop has two standards that disagree by four microns and no way to tell which room a given measurement was taken in. Every part still passes inspection. The certificates still read pass. The parts come back from the customer. That is the whole danger of a constant: a value that everything trusts because nobody can change it is only trustworthy while there is exactly one of it.
Syntax or Core Structure
PHP has two ways to seal a value and they are not interchangeable. const is a declaration the compiler handles: the name and its value are fixed while the file is being compiled, so the value must be a constant expression and the declaration cannot sit inside an if. define() is an ordinary function call that happens when execution reaches it, so it accepts any expression at all and can be made conditional. Both produce a global, case-sensitive name that cannot be reassigned and cannot be unset().
<?php
declare(strict_types=1);
const SHIFT_START = 6; // compile time, no condition allowed
const SHIFT_END = SHIFT_START + 8; // other constants are allowed
const GRADE_LIMITS = ['h6' => 13, 'h7' => 21]; // arrays: const since PHP 5.6
define('BENCH', 'north bay'); // run time, any expression
define('BENCH_LABEL', strtoupper(BENCH) . ' bench');
echo SHIFT_START, " to ", SHIFT_END, PHP_EOL;
echo BENCH_LABEL, PHP_EOL;
echo GRADE_LIMITS['h7'], PHP_EOL; // dereference it directly
var_dump(defined('BENCH'), defined('bench')); // names are case sensitive
echo constant('BENCH'), PHP_EOL; // look one up by name
$which = 'GRADE_LIMITS';
echo constant($which)['h6'], PHP_EOL; // dynamic lookup, then index
if (!defined('CALIBRATED_ON')) {
define('CALIBRATED_ON', 'day 12'); // only define() can be conditional
}
echo CALIBRATED_ON, PHP_EOL;
echo defined('SHIFT_START') ? 'sealed' : 'missing', PHP_EOL;
Output:
6 to 14
NORTH BAY bench
21
bool(true)
bool(false)
north bay
13
day 12
sealed
Four details in that listing are worth stopping on. SHIFT_END was computed from another constant, which the compiler is happy to fold because the answer is knowable without running anything. BENCH_LABEL called strtoupper(), which const would have rejected outright -- a function call is not a constant expression. defined() disagreed about BENCH and bench, because constant names have been strictly case-sensitive since the case-insensitive third argument to define() was removed in PHP 8.0. And constant($which) fetched a constant whose name was only known at run time, which is the only way to reach one dynamically: there is no $$CONST form and no way to interpolate a constant into a double-quoted string.
Note also what did not appear: any attempt to change one. Assigning to a constant is a parse error, redefining one with define() raises a warning and leaves the original in place, and unset() will not accept a constant name at all. That is the entire behavioural contract, and it is why constants are the right home for values that describe the program rather than the request it is handling.
Technical Depth: What A Sealed Value Really Costs
const And define() Are Not The Same Tool
| Question | const NAME = ... | define('NAME', ...) |
|---|---|---|
| When is it fixed | compile time | when execution reaches the call |
| Allowed value | constant expression only | any expression |
| Can be conditional | no | yes |
| Namespaced | yes, by the current namespace | no, unless the name contains it |
| Legal inside a class | yes, this is a class constant | no |
| Names not valid as identifiers | rejected | accepted, reachable via constant() |
| Visible before its own line | yes, within the file | no |
| Arrays permitted | since PHP 5.6 | since PHP 7.0 |
The namespace row is the one that catches teams out. Written inside namespace Works\Inspection;, const TEMP = 20; creates Works\Inspection\TEMP, which an unqualified TEMP elsewhere will not find; define('TEMP', 20) creates a single global TEMP regardless of where the call was written. Mixing the two in one codebase produces a constant that resolves in some files and not others, and the error is a fatal "undefined constant" a long way from the declaration.
The compile-time distinction has a second consequence that matters under OPcache. A const is resolved while the file is compiled, and the compiled form is what gets cached and reused for every subsequent request, so the lookup costs nothing at run time. A define() call is a function call in the cached opcodes and executes on every single request. For a handful of names this is unmeasurable; for a bootstrap file that defines two hundred of them it is real work repeated on every hit.
Class Constants, Visibility And Late Static Binding
Inside a class, const declares a class constant: still immutable, but now with a visibility modifier available since PHP 7.1 and a final modifier since PHP 8.1. Class constants can be redeclared by a subclass, which is where the two resolution keywords start to matter. self:: means "the class this line was written in". static:: means "the class the call was made against".
<?php
declare(strict_types=1);
class Master
{
public const SET = 'metric slip gauges';
public const TEMP = 20;
protected const CASE_NO = 4;
private const SERIAL = 'M-1187';
public static function describeSelf(): string
{
return self::SET . ' at ' . self::TEMP . ' C';
}
public static function describeLate(): string
{
return static::SET . ' at ' . static::TEMP . ' C';
}
public static function caseNumber(): int
{
return static::CASE_NO;
}
public static function serial(): string
{
return self::SERIAL; // private, so only this class body may read it
}
}
class Working extends Master
{
public const SET = 'shop floor gauges';
public const TEMP = 23;
protected const CASE_NO = 9;
}
echo Master::SET, PHP_EOL;
echo Working::SET, PHP_EOL;
echo Master::describeSelf(), PHP_EOL;
echo Working::describeSelf(), PHP_EOL; // self:: still resolves to Master
echo Working::describeLate(), PHP_EOL; // static:: follows the called class
echo Working::caseNumber(), PHP_EOL;
echo Master::serial(), PHP_EOL;
echo Working::class, PHP_EOL;
Output:
metric slip gauges
shop floor gauges
metric slip gauges at 20 C
metric slip gauges at 20 C
shop floor gauges at 23 C
9
M-1187
Working
Lines three and four are the same text from two different classes, and that is the result people find surprising. Working::describeSelf() ran the method it inherited, and self:: inside that method was resolved when Master was compiled, so it reads Master's values however it is called. describeLate() is character-for-character identical except for the keyword, and it reports the subclass. If you intend a constant to be a default that children may replace, every reference to it inside the parent has to be static::; if you intend it to be a fixed property of that one class, use self:: and mark it final so nobody redeclares it by accident.
The visibility modifiers behave as they do on properties, with one difference worth knowing: private const is genuinely private to the declaring class, so a subclass that declares its own private const SERIAL is not overriding anything -- the two are separate constants that happen to share a name. Interface constants are always public, and before PHP 8.1 a class could not override one it inherited from an interface at all.
The Magic Constants
Nine names look like constants but are not: the compiler substitutes them with a value that depends on where the line was written. They are not variables, they are not stored anywhere, and they cannot be reassigned or passed by reference.
| Name | Substituted with |
|---|---|
__LINE__ | the line number of the line it appears on |
__FILE__ | the absolute path of the file, symlinks resolved |
__DIR__ | the directory part of that path, no trailing slash |
__FUNCTION__ | the current function name, or the method name inside a method |
__CLASS__ | the current class name including its namespace |
__METHOD__ | the class and method joined by a double colon |
__NAMESPACE__ | the current namespace, or the empty string at global scope |
__TRAIT__ | the name of the trait the line was written in |
ClassName::class | the fully qualified name of that class, as a string |
Two of those are traps for anything you want to test. __FILE__ and __DIR__ are absolute paths that differ on every machine, so a value derived from them must never appear in an assertion or a golden output file -- take basename(__FILE__) if what you actually wanted was the file's name. Everything else on the list is fixed by the source text and is therefore perfectly testable.
The listing below is numbered from <?php as line 1, which is how PHP counts, so the two __LINE__ values can be read straight off it. Save it as gauge.php.
<?php
declare(strict_types=1);
// this file is saved as gauge.php
function stamp(): string
{
return __FUNCTION__ . ' at line ' . __LINE__;
}
class Press
{
public function mark(): string
{
return __CLASS__ . ' :: ' . __FUNCTION__ . ' :: ' . __METHOD__;
}
}
echo basename(__FILE__), PHP_EOL;
echo stamp(), PHP_EOL;
echo (new Press())->mark(), PHP_EOL;
echo Press::class, PHP_EOL;
echo 'this echo is on line ', __LINE__, PHP_EOL;
Output:
gauge.php
stamp at line 7
Press :: mark :: Press::mark
Press
this echo is on line 22
__FUNCTION__ inside a method gives the bare method name, while __METHOD__ gives the qualified form -- which is the one you almost always want in a log line, because mark on its own tells a reader nothing. __LINE__ reported 7 from inside stamp(), not the line of the call, because substitution happens where the token is written and the function body is compiled once. And Press::class worked without instantiating anything: it is resolved by the compiler from the use statements in scope, so it survives renaming in a way that the string 'Press' does not.
Constant Expressions, Array Constants And Platform Values
A constant expression is anything the compiler can evaluate without running your code: literals, arithmetic and string concatenation, other constants, array literals built from those, and the ternary and null-coalescing operators. What it excludes is anything that could differ between two runs -- function calls, variables, object property reads. The interesting consequence is that a constant may hold an array, and an array in PHP is a value, so reading a constant array hands you a copy.
<?php
declare(strict_types=1);
class Bay
{
public const WIDTH = 4;
public const DEPTH = 3;
public const SLOTS = self::WIDTH * self::DEPTH; // folded at compile time
public const LABEL = 'bay ' . self::WIDTH . 'x' . self::DEPTH;
public const RACKS = ['top' => self::SLOTS, 'low' => self::SLOTS];
}
echo Bay::SLOTS, ' ', Bay::LABEL, PHP_EOL;
echo Bay::RACKS['top'], PHP_EOL;
$racks = Bay::RACKS; // a copy, exactly like any other array assignment
$racks['top'] = 99;
echo 'copy : ', $racks['top'], PHP_EOL;
echo 'const : ', Bay::RACKS['top'], PHP_EOL;
// the three lines below describe the build, not the program
echo PHP_INT_SIZE, ' bytes per int', PHP_EOL;
echo PHP_INT_MAX === 9223372036854775807 ? 'a 64-bit build' : 'not 64-bit', PHP_EOL;
echo strlen(PHP_EOL), ' byte line ending', PHP_EOL;
Output (the last three lines are platform-dependent; this is a 64-bit Linux or macOS build, where PHP_EOL is one byte -- on Windows it is two):
12 bay 4x3
12
copy : 99
const : 12
8 bytes per int
a 64-bit build
1 byte line ending
The middle pair is the one to remember. $racks was modified and Bay::RACKS was not, because the assignment copied the array out of the constant. This makes array constants safe to hand around, but it also means they are not a cheap lookup table: every read of Bay::RACKS in a loop is a potential array copy, whereas Bay::RACKS['top'] reads one element without copying anything. Reach for a class constant when the table is small and fixed, and for an injected value when it is large or when a test might want to replace it.
Real World Example: The Gauge Room Certification Sheet
A batch of eight turned shafts has come off the lathes and each one has been measured on a bench comparator. The nominal size is 25 mm and everything is recorded in microns, so the arithmetic stays in integers. Two things stand between the raw reading and a verdict. The reading was taken at whatever temperature the shop happened to be, and steel grows about twelve microns per metre per degree, so each measurement has to be corrected back to the reference temperature of twenty degrees. Then the corrected deviation from nominal is compared against the ISO tolerance for the grade the drawing calls for: thirteen microns for h6, twenty-one for h7, thirty-three for h8.
Every fixed figure in that description is a constant, and they are deliberately declared in three different places to show what each home is for: the tolerance table and the nominal size are public class constants because callers legitimately need to read them, the reference temperature and the expansion coefficient are private because they are the class's own working figures, and the room name is a define() because a site is allowed to set it before the file is included.
<?php
declare(strict_types=1);
// a runtime constant: a site may define this before including the report
if (!defined('SITE_ROOM')) {
define('SITE_ROOM', 'gauge room 2');
}
final class Gauge
{
public const GRADES = ['h6' => 13, 'h7' => 21, 'h8' => 33]; // microns
public const NOMINAL = 25000; // microns
private const MASTER_TEMP = 20; // degrees C
private const ALPHA = 12; // microns per metre per degree
private const FMT = "%-6s %-5s %6s %3s %4s %6s %4s %3s %7s";
private const W = 52;
public static function growth(int $temp): int
{
return intdiv(self::NOMINAL * self::ALPHA * ($temp - self::MASTER_TEMP), 1000000);
}
/**
* @param list<array{0:string, 1:string, 2:int, 3:int}> $batch
*/
public static function certify(array $batch): void
{
$rows = [];
$band = [];
$passed = 0;
foreach ($batch as [$part, $grade, $measured, $temp]) {
$grow = self::growth($temp);
$corrected = $measured - $grow;
$dev = $corrected - self::NOMINAL;
$tol = self::GRADES[$grade];
$ok = abs($dev) <= $tol;
$passed += $ok ? 1 : 0;
$rows[] = [$part, $grade, $measured, $temp, $grow, $corrected,
sprintf("%+d", $dev), $tol, $ok ? 'pass' : 'REJECT'];
$band[$grade]['n'] = ($band[$grade]['n'] ?? 0) + 1;
$band[$grade]['ok'] = ($band[$grade]['ok'] ?? 0) + ($ok ? 1 : 0);
$band[$grade]['worst'] = max($band[$grade]['worst'] ?? 0, abs($dev));
}
printf("GAUGE ROOM CERTIFICATION -- %s%s", strtoupper(SITE_ROOM), PHP_EOL);
echo str_repeat("=", self::W), PHP_EOL;
printf(self::FMT . "%s", "PART", "GRADE", "MEAS", "T", "GROW", "CORR",
"DEV", "TOL", "VERDICT", PHP_EOL);
echo str_repeat("-", self::W), PHP_EOL;
foreach ($rows as $r) {
printf(self::FMT . "%s", $r[0], $r[1], $r[2], $r[3], $r[4], $r[5],
$r[6], $r[7], $r[8], PHP_EOL);
}
echo str_repeat("-", self::W), PHP_EOL;
// GRADES fixes the band order, so it cannot follow measurement order
foreach (array_keys(self::GRADES) as $grade) {
$b = $band[$grade] ?? ['n' => 0, 'ok' => 0, 'worst' => 0];
printf(self::FMT . "%s", "", $grade, "", "", "", "", $b['worst'],
self::GRADES[$grade], $b['ok'] . " of " . $b['n'], PHP_EOL);
}
echo str_repeat("-", self::W), PHP_EOL;
printf(self::FMT . "%s", "", "TOTAL", "", "", "", "", "", "",
$passed . " of " . count($rows), PHP_EOL);
echo str_repeat("=", self::W), PHP_EOL;
printf("master %d C nominal %d um alpha %d um/m/C%s",
self::MASTER_TEMP, self::NOMINAL, self::ALPHA, PHP_EOL);
printf("report by %s in %s%s", self::class, basename(__FILE__), PHP_EOL);
printf("%d of %d parts outside tolerance%s",
count($rows) - $passed, count($rows), PHP_EOL);
}
}
Gauge::certify([
['A-101', 'h6', 25008, 24],
['A-102', 'h6', 25014, 24],
['A-103', 'h7', 25019, 28],
['B-207', 'h7', 24996, 20],
['B-208', 'h8', 25031, 22],
['C-330', 'h8', 25036, 26],
['C-331', 'h6', 24994, 20],
['D-412', 'h6', 25022, 24],
]);
Output:
GAUGE ROOM CERTIFICATION -- GAUGE ROOM 2
====================================================
PART GRADE MEAS T GROW CORR DEV TOL VERDICT
----------------------------------------------------
A-101 h6 25008 24 1 25007 +7 13 pass
A-102 h6 25014 24 1 25013 +13 13 pass
A-103 h7 25019 28 2 25017 +17 21 pass
B-207 h7 24996 20 0 24996 -4 21 pass
B-208 h8 25031 22 0 25031 +31 33 pass
C-330 h8 25036 26 1 25035 +35 33 REJECT
C-331 h6 24994 20 0 24994 -6 13 pass
D-412 h6 25022 24 1 25021 +21 13 REJECT
----------------------------------------------------
h6 21 13 3 of 4
h7 17 21 2 of 2
h8 35 33 1 of 2
----------------------------------------------------
TOTAL 6 of 8
====================================================
master 20 C nominal 25000 um alpha 12 um/m/C
report by Gauge in gauge.php
2 of 8 parts outside tolerance
Every fixed fact the gauge room owns is a constant, and every one of them is read at least once while the report is printed. NOMINAL is the size the customer ordered, in microns, so that no float ever enters the calculation. ALPHA is the expansion coefficient of the steel in microns per metre per degree, which is why the growth formula divides by a million: a 25000 micron part is 0.025 of a metre, and intdiv performs the whole correction in integers rather than trusting a decimal. MASTER_TEMP is the 20 C the reference set was certified at, and it appears twice -- once in growth() as the datum the deviation is measured from, and once in the footer, so the sheet states the assumption it was computed under. GRADES is an array constant holding the three tolerance bands; it is public because the front office quotes those numbers to customers, while SERIAL and CASE_NO in the earlier example stayed private because nobody outside the class has any business knowing them.
Read the C-330 row against the C-331 row and the point of the whole exercise becomes visible. C-330 measured 25036 microns, which is 36 over nominal, at 26 C. The growth term is intdiv(25000 * 12 * 6, 1000000), which is 1 micron, so the corrected size is 25035 and the deviation is +35 against an h8 tolerance of 33: rejected by two microns. C-331 measured 24994 at exactly the master temperature, so its growth term is zero, its corrected size is its measured size, and -6 against an h6 tolerance of 13 passes comfortably. D-412 is the row that would have escaped a less careful shop -- 25022 measured at 24 C corrects to 25021, a deviation of +21, which would sail through h7's 21 and h8's 33 but fails h6's 13. The same steel is a good part or a scrap part depending only on which line of GRADES applies to it, and that is exactly the kind of number that must live in one named place.
Two of the constants have nothing to do with metrology and everything to do with the sheet being readable. FMT holds the nine field widths, so the header row, the eight part rows, the three band rows and the total row are all laid out by the same string, and W holds the width of the rules that separate them. Because the band rows iterate array_keys(self::GRADES) rather than the keys of $band, the h6, h7, h8 order on the sheet is fixed by the constant and not by whichever grade happened to be measured first; feed the batch in a different order and the report is byte-identical. The footer uses self::class and basename(__FILE__) so the sheet says which class and which file produced it, which is what an auditor asks first. Note that it is basename(__FILE__) and not __FILE__: the bare magic constant would print the absolute path of the machine that ran the job, which changes between the development box and the works server and makes two otherwise identical reports differ.
The real design flaw is in the tolerance lookup. self::GRADES[$grade] assumes the grade string is one of the three keys, and if a batch arrives with h9 -- a grade the shop does genuinely use for coarse work -- PHP 8 emits an "Undefined array key" warning and evaluates the expression to null. The comparison abs($dev) <= null then compares against zero, so every h9 part is rejected unless it measured exactly nominal, and because the band loop walks the constant's keys, no h9 band row is printed at all. The TOTAL row still counts those rows, so the bands silently stop summing to the total and the sheet is internally inconsistent while looking perfectly well formed. The fix is to check array_key_exists($grade, self::GRADES) and fail loudly, or better, to make the grade an enum so an unknown one cannot be constructed. Two smaller limits are worth naming as well: W is a hand-maintained 52 that nothing checks against the widths inside FMT, so widening one column silently leaves every rule line the wrong length, and growth() computes expansion from NOMINAL, which means this class can only certify parts of that one size -- a second part size needs a second class, or the nominal size needs to stop being a constant and become a constructor argument.
Common Mistakes
- Putting a dollar sign on a constant.
echo $NOMINAL;reads an
undefined variable and prints nothing plus a warning, while echo NOMINAL; reads the constant. Constants have no sigil, which also means they do not interpolate: "size is NOMINAL" prints the word, not the value. You must concatenate, or pass the constant to printf, or wrap it as "size is {$x}" after assigning it to a variable first.
- Assuming an undefined constant is null or false. In PHP 7 a bare
undefined FOO raised a notice and fell back to the string "FOO", which made typos evaluate to something truthy and hid them for years. Since PHP 8 the same code throws Error: Undefined constant "FOO". Do not test a constant by using it; test it with defined('FOO').
- **Quoting the name when reading, or forgetting to quote it when
defining.** define('BENCH', 'north bay') takes the name as a string, defined('BENCH') takes it as a string, constant('BENCH') takes it as a string -- but plain BENCH in an expression does not. Mixing these up gives you either the six characters "BENCH" where you wanted the value, or an undefined-constant Error where you wanted the name.
- Reaching for
define()whenconstwould do.define()is
resolved at run time, is invisible to static analysers and IDEs, defines into the global namespace regardless of the enclosing namespace statement, and is not folded into OPcache's compiled output. Use const at file or class scope by default, and keep define() for the two cases that need it: a name computed at run time, and a value that is not a constant expression.
- Redefining and expecting a clear failure. A second
const FOOin the
same scope is a fatal compile error, but a second define('FOO', ...) only emits a warning and leaves the first value in place. That is a silent misconfiguration: the code that runs is whichever file was included first, and nothing in the output says so. Guard with if (!defined('FOO')) only when you genuinely want the first definition to win, and say so in a comment.
- Treating a class constant as immutable data when it holds an array.
Bay::RACKS cannot be reassigned, but $copy = Bay::RACKS; hands you an ordinary array you can modify freely, and any object stored inside a constant array is still shared by reference, so its properties can be mutated. The binding is constant; deep immutability is not.
- Using
self::where you meantstatic::.self::TEMPis
resolved at compile time against the class the code was written in, so a subclass that overrides TEMP is ignored. static::TEMP resolves at run time against the called class. The two produced 20 and 23 in the earlier example from identical-looking method bodies, and this is the single most common source of "my override does nothing" bug reports.
- Forgetting that class constants are public by default. `const
SERIAL = 'M-1187'; inside a class is world-readable, so anything that can name the class can read it. Mark internal values private or protected explicitly. Conversely, do not put secrets in constants at all -- they are baked into the source, they appear in stack traces and var_dump` output of reflection objects, and they cannot be rotated without a deploy.
- Printing
__FILE__or__DIR__in output a human compares. Both
are absolute paths, so the same script produces different text on a developer machine, a CI runner and a server, and any test that asserts on the output fails for reasons that have nothing to do with the code. Use basename(__FILE__) in reports, and keep __DIR__ for building include paths, which is what it is genuinely good at.
Best Practices
- Default to
const, and reach fordefine()only when the name or the
value has to be computed at run time. const is namespaced, visible to tooling, cheaper at run time and impossible to define twice by accident.
- Put every constant that describes one subject on the class that owns that
subject, not in a global config.php. Gauge::NOMINAL tells the reader which part of the system decides that number; a global NOMINAL tells them nothing and can be read from anywhere.
- Give class constants explicit visibility. Write
public constwhen the
value is part of the contract and private const when it is an implementation detail, so that changing the latter is not a breaking change.
- Keep units in the name or in a comment on the same line, and prefer
integers in the smallest unit you care about. NOMINAL = 25000 with // microns cannot be confused with millimetres, and integer arithmetic on microns has no rounding behaviour to reason about.
- Derive constants from each other rather than repeating arithmetic.
const SHIFT_END = SHIFT_START + 8; and const SLOTS = self::WIDTH * self::DEPTH; are evaluated once at compile time and can never disagree with their inputs, which two separately typed numbers eventually will.
- Use
static::for a constant a subclass is expected to override and
self:: for one it is not, and choose deliberately rather than by habit. Reading self:: should tell a maintainer "this value is fixed here".
- Prefer an enum over a set of related string or integer constants when the
value is a closed set of choices. An enum makes an unknown grade impossible to construct, whereas GRADES['h9'] is a warning and a null that the rest of the code happily computes with.
- Never store secrets, credentials or per-environment endpoints in
constants defined in committed source. Read them from the environment at startup, validate them there, and if you want a constant, define it once from the validated value so the rest of the codebase still has a single name to use.
Practice Exercises
- The chalked slate. Write a file that defines
ROOMwithconst
and SHIFT with define(), then prints, for each of the two names, whether it is defined, its value fetched through constant(), and the value fetched by naming it directly. Add a second define('SHIFT', 'nights') at the bottom and a second const ROOM in a comment, and write down in a comment what happens in each case and why one is a warning and the other a fatal error.
- Tolerance bands. Build a class
Borewith a public array constant of
at least four grade names mapped to integer tolerances in microns, a private integer NOMINAL, and a static method that takes a grade and a measured size and returns 'pass' or 'REJECT'. Then make it safe: reject an unknown grade with a thrown exception instead of the null comparison described above, and prove it by calling the method with a grade that is not in the constant.
- Late static binding. Write a base class with
const TEMP = 20;and
two methods that report the temperature, one using self::TEMP and one using static::TEMP. Subclass it, override TEMP with 23, and call all four methods, printing the class name alongside each result with static::class. Then mark the base constant final and record the exact error you get.
- A stamped report. Take the certification report from this lesson and
add a fourth grade to GRADES, three more parts to the batch that use it, and a header line that prints the file name with basename(__FILE__) and the class name with self::class. Confirm that the grade band rows still appear in the order the constant lists them regardless of the order the parts are fed in, and that your new band's n of m counts still add up to the TOTAL row.