Originally published on decentphp.dev — part of the Writing decent PHP course. View this lesson on the original site.
A name should answer "what unit is this in?"
A variable called $timeout raises an immediate question: seconds? milliseconds? minutes?
A variable called $weight is the same: kilograms? pounds? grams?
A variable called $price could be in pounds, pence, dollars, or cents.
You should not have to dig through the function body, the database schema, or another developer's memory to answer that. Put the unit in the name.
Before
The names look "clean", but every one of them hides a question.
<?php
function chargeCustomer(array $customer, int $amount, int $timeout): bool
{
$balance = $customer['balance'];
if ($balance < $amount) {
return false;
}
$delay = $timeout * 1000;
sleep($delay);
return true;
}
Pause and try to answer:
- is
$amountin pounds or pence? - is
$balancein the same unit as$amount? - is
$timeoutin seconds, and what is$delayafter multiplying by 1000? - if you call
chargeCustomer($customer, 10, 5), what does that actually do?
The function compiles, but the call site is a guessing game.
After
The same code with units and scale baked into the names.
<?php
function chargeCustomer(array $customer, int $amountInPence, int $timeoutSeconds): bool
{
$balanceInPence = $customer['balance_in_pence'];
if ($balanceInPence < $amountInPence) {
return false;
}
$delayMilliseconds = $timeoutSeconds * 1000;
usleep($delayMilliseconds * 1000);
return true;
}
Now the call chargeCustomer($customer, 1000, 5) is unambiguous: charge 1000 pence (£10) and wait up to 5 seconds.
Why this version is better
- the unit is part of the contract, not a hidden assumption
- mismatched units (pounds vs pence) become visible at the call site, not at runtime
- code review can spot a bug like "this is in milliseconds but you passed seconds" without reading any other file
- new developers do not need tribal knowledge to use the function safely
Common name suffixes worth using
| Concept | Vague | Better |
|---|---|---|
| Money | $price, $amount |
$priceInPence, $amountInPence |
| Duration | $timeout, $delay |
$timeoutSeconds, $delayMilliseconds |
| Distance | $distance |
$distanceKm, $distanceMetres |
| Weight | $weight |
$weightKg, $weightGrams |
| File size | $size |
$sizeBytes, $sizeMb |
| Percentages | $discount |
$discountPercent, $discountFraction |
| Counts vs ids | $user |
$userId, $userCount |
| Dates and times | $created |
$createdAt, $createdAtTimestamp |
A small unit smell test
When you read a variable name, ask: can two reasonable developers disagree about what unit this is in?
If yes, the name is missing information. The fix is almost always one extra word. That one word stops a whole class of "off by 1000" bugs before they ever ship.
From Writing decent PHP — Naming variables, functions, classes, and files well