The Analogy: The Structural Engineer's Plan Check
Before a single foundation is poured, a structural engineer sits down with the drawings and the load calculations. They trace every load from the roof down through the beams, the columns, and the footings into the ground, checking that each member is strong enough for whatever rests on it. Nothing has been built. The entire examination happens on paper, reasoning about the structure from its description alone.
This catches a whole class of faults that would otherwise reveal themselves only under load: a beam sized for a lighter roof than the one actually specified, a column whose load path never quite reaches a footing, a cantilever that would deflect too far. The engineer finds these by following the rules of statics through the design, not by building the thing and watching what sags. A fault found on the drawing costs an eraser; the same fault found after construction costs a demolition.
The check has levels of strictness. A quick review might confirm only that every beam has a size and every load has somewhere to go. A rigorous one verifies deflection limits, connection details, fire ratings, and seismic behaviour, and flags anything the drawings leave ambiguous. Raising the strictness surfaces more potential problems, but it also demands that the drawings be specified more completely: a vague note that "the contractor will size this on site" sails through a loose check and is rejected by a strict one.
The plan check has a hard boundary. It verifies that the structure is consistent with its own drawings and with the rules of statics, but it cannot tell whether the drawings describe the building the client actually wanted. A perfectly sound structure can be drawn for the wrong site, with the rooms in the wrong places, and every calculation will still balance. The check proves internal consistency and code-compliance, not fitness for purpose, and mistaking the one for the other is how a flawless set of drawings yields a useless building.
Syntax or Core Structure
Static analysis reads your code without running it and reports the errors it can prove will occur -- type mismatches, method calls on null, undefined variables -- before a single request reaches the code. PHPStan and Psalm are the two standard tools; neither is installed in this runtime, so the lesson demonstrates the bugs they catch by showing what PHP does at runtime, which is either to crash late or to produce a wrong result silently, and describes what the analyser would report ahead of time. The foundation is PHP's own type system: with declare(strict_types=1) at the top of a file, the engine enforces parameter and return types exactly.
<?php
declare(strict_types=1);
function half(int $n): float {
return $n / 2;
}
echo half(10), "\n";
try {
half('ten');
} catch (TypeError $e) {
echo "rejected non-int argument\n";
}
Output:
5
rejected non-int argument
The half function declares that it takes an int and returns a float. Under strict_types, calling it with the string 'ten' raises a TypeError rather than silently coercing, so the wrong type is caught at the boundary. A static analyser goes one step further: it reports that exact bad call at analysis time, from reading the code, so you never have to reach the line in production to discover the argument is wrong. Native type declarations are the raw material the analyser reasons about -- the more precisely you type your code, the more it can prove.
Technical Depth: PHPDoc, Levels, and the Bugs Caught
Expressing what native types cannot
Native types stop at array; they cannot say what is inside one. PHPStan and Psalm read structured PHPDoc annotations to recover that lost precision.
| PHPDoc type | Means | Why native types cannot |
|---|---|---|
list<int> | Zero-indexed array of ints | array cannot state its element type |
array<string, User> | Map of string keys to User | keys and values are untyped natively |
array{id: int, name: string} | An exact keyed shape | native arrays carry no shape |
non-empty-string | A string proven not empty | string still allows the empty string |
positive-int | An int greater than zero | int allows zero and negatives |
With a shape annotation, the analyser knows the keys a returned array will have and their types, so it can flag a caller that reads a key you never set.
<?php
declare(strict_types=1);
/**
* @param list<int> $numbers
* @return array{count: int, total: int, average: float}
*/
function stats(array $numbers): array {
$total = array_sum($numbers);
$count = count($numbers);
return [
'count' => $count,
'total' => $total,
'average' => $count > 0 ? $total / $count : 0.0,
];
}
$s = stats([4, 8, 15, 16, 23, 42]);
echo 'count=', $s['count'], ' total=', $s['total'], ' average=', $s['average'], "\n";
Output:
count=6 total=108 average=18
At runtime the docblock is inert -- PHP ignores comments entirely, and the function simply returns an array. Its value is to the analyser: the @return array{...} shape lets it prove that $s['count'] exists and is an int, and it would report $s['median'] as an access to an undefined key without ever running the code.
Analysis levels
Both tools grade strictness by level, and you raise the level as the codebase gets cleaner. Higher levels demand more complete annotations, exactly as a stricter plan check demands more complete drawings.
| Level | Roughly checks |
|---|---|
| 0 to 2 | Unknown classes, functions, methods; obvious mistakes |
| 3 to 5 | Return, property, and argument types line up |
| 6 | Missing type annotations are reported |
| 7 | Union-type and nullability mistakes |
| 8 | Calling a method on a possibly-null value |
| 9 | Strict treatment of the mixed type |
Type narrowing across branches
A static analyser does not just look at a variable's declared type; it tracks how that type is narrowed by the checks around it. Inside an is_int branch the analyser knows the value is an int, and in the other branch it knows the value is whatever remains of the union.
<?php
declare(strict_types=1);
/** @param int|string $id */
function label(int|string $id): string {
if (is_int($id)) {
return 'number ' . ($id * 10);
}
return 'text ' . strtoupper($id);
}
echo label(7), "\n";
echo label('abc'), "\n";
Output:
number 70
text ABC
The parameter is the union int|string. Inside the is_int branch the analyser narrows it to int, so $id * 10 is valid arithmetic; in the fall-through branch it narrows to string, so strtoupper($id) is valid. Move strtoupper above the check, where $id is still int|string, and the analyser reports that a string function may receive an int -- a mistake the runtime would only expose on the wrong input. This flow-sensitive narrowing is what lets unions be both precise and safe.
The class of bug it catches
The most valuable catch is the method call on a value that might be null. PHP runs such code happily until the null path is actually taken, and then it throws.
<?php
declare(strict_types=1);
final class User {
public function __construct(public string $name) {}
public function greet(): string { return "Hi, {$this->name}"; }
}
/** @param array<string, User> $users */
function find(array $users, string $id): ?User {
return $users[$id] ?? null;
}
$users = ['u1' => new User('Alice')];
$u = find($users, 'u1');
echo $u !== null ? $u->greet() : 'not found', "\n";
$missing = find($users, 'u2');
echo 'lookup u2: ';
try {
echo $missing->greet(), "\n";
} catch (Error $e) {
echo "Error: call on null\n";
}
Output:
Hi, Alice
lookup u2: Error: call on null
find is honestly typed as returning ?User, so the analyser knows every result might be null. The first caller checks for null and is fine. The second calls $missing->greet() directly, and PHP throws an Error the moment that line runs on a miss. At level 8 a static analyser reports this line -- "cannot call method greet() on possibly null User" -- from reading the code, so the bug is fixed before it ever reaches the null path in production.
Real World Example: A Typed Inventory Summary
A stock report reads rows of inventory -- each a SKU, a quantity, and a unit price in cents -- and produces a summary of line count, total units, and total value. The two docblocks below carry the real precision: the parameter is a list of shaped rows, and the return value is itself an exact shape. A strict analyser reads both and checks every access against them.
<?php
declare(strict_types=1);
/**
* @param list<array{sku: string, qty: int, price: int}> $rows
* @return array{lines: int, units: int, value: int}
*/
function summarise(array $rows): array {
$units = 0;
$value = 0;
foreach ($rows as $r) {
$units += $r['qty'];
$value += $r['qty'] * $r['price'];
}
return ['lines' => count($rows), 'units' => $units, 'value' => $value];
}
function money(int $cents): string {
return '$' . number_format($cents / 100, 2);
}
$rows = [
['sku' => 'A1', 'qty' => 3, 'price' => 1200],
['sku' => 'B2', 'qty' => 10, 'price' => 550],
['sku' => 'C3', 'qty' => 2, 'price' => 9999],
];
$report = summarise($rows);
echo 'lines: ', $report['lines'], "\n";
echo 'units: ', $report['units'], "\n";
echo 'value: ', money($report['value']), "\n";
Output:
lines: 3
units: 15
value: $290.98
The summarise function walks the rows once, accumulating units and value, and returns the three-key shape its docblock promises. Because the analyser knows each $r has qty and price as ints, it accepts $r['qty'] * $r['price'] as integer arithmetic and would object immediately if a row were missing price or if the code read $r['cost']. The three rows total fifteen units and 29098 cents, which money formats as $290.98 -- number_format supplies the two decimal places, and would add a thousands comma for any value at or above 100000 cents.
The strength on display is that the whole chain is proven consistent without running it. The analyser confirms that summarise receives the shape it declares, returns the shape it declares, and that every caller reads only keys that exist with the types they hold. Raise the level and it will also insist that no step quietly relies on mixed, forcing each value to have a known type from input to output. None of this required a test to run or a request to arrive.
The design flaw is the boundary the plan check cannot cross: static analysis proves that the types and shapes are consistent, never that the values or the logic are correct. If summarise accumulated $r['qty'] * $r['qty'] by mistake, every type would still line up perfectly -- int times int is an int, the shape is unchanged -- and the analyser would pass it without complaint while the reported value was nonsense. Only a test comparing the output against a total computed by hand catches that. Static analysis and testing are complementary, not substitutes: the analyser rules out entire classes of type and null errors cheaply and early, but it says nothing about whether your arithmetic means what you intended.
Common Mistakes
- Leaving parameters and returns untyped. An untyped
function process($data)gives the analyser nothing to reason about, so it cannot catch a wrong argument. Declare native types wherever the language allows.
- Overusing
mixed. Themixedtype accepts anything and defeats analysis on that value. Narrow it to the actual types, using a union such asint|stringonly when several are genuinely possible.
- Suppressing errors instead of fixing them. An ignore annotation silences the tool but leaves the bug in place. Reserve suppression for genuine false positives, and note why next to each one.
- Starting a legacy project at the highest level. Jumping straight to the top level buries you in thousands of errors at once. Start low, fix to green, then raise the level one step at a time.
- Treating a green analysis as proof of correctness. The tool proves type and null consistency, not that the logic is right. A well-typed function can still compute the wrong answer, so keep your tests.
- Typing an array as just
array. The barearraytells the analyser nothing about keys or elements. Uselist<T>,array<K, V>, or anarray{...}shape so element access can be checked.
- Ignoring nullability. Returning
?Userbut never handling the null in callers is among the commonest real bugs. Let the analyser force a null check at every use.
- Not running the analyser in CI. If analysis runs only on your machine, the codebase drifts as teammates push untyped code. Run it on every pull request and fail the build on new errors.
- Writing docblocks that disagree with the code. A
@return stringon a method that can also return null misleads both readers and the analyser. Keep every annotation exactly in step with what the code does.
Best Practices
- Type every parameter, return, and property natively, and add PHPDoc only for the precision native types cannot express.
- Adopt the tool at a level you can reach green today, then ratchet the level up one step at a time as you clear errors.
- Prefer precise array types --
list<int>,array<string, User>, andarray{...}shapes -- over the barearray.
- Enable
strict_typesin every file so the runtime and the analyser agree on how types behave.
- Handle nullability explicitly: check a
?Tresult before using it, and let the analyser enforce that at level 8 and above.
- Run the analyser in continuous integration and fail the build on new errors, so the baseline only ever improves.
- Fix errors rather than suppressing them; when a suppression is genuinely warranted, record the reason beside it.
- Pair analysis with tests: let the analyser cover type and null safety, and let tests cover values and behaviour.
Practice Exercises
- Add native types and a shape docblock to an untyped
function totals($rows)so a strict analyser could verify its callers, and state which key accesses it could then prove safe.
- Write a function typed to return
?intfrom a search over an array, plus two callers -- one that handles the null result and one that does not -- and explain which line a level-8 analyser would flag.
- Take the
summarisefunction and introduce a deliberate value bug that still type-checks, such as multiplyingqtybyqty; then write a unit test that catches it, demonstrating why analysis alone is insufficient.
- Annotate a function that returns
array<string, list<int>>-- a map from a name to a list of scores -- and write a caller that iterates it, ensuring every access matches the declared shape.