Below is a “mental model” you can keep in your back-pocket when dealing with PHP’s type system.
I’ll start with the fundamentals and then zoom in on (1) closures and (2) “Array” a.k.a. generic-style arrays.
- Two worlds you need to juggle
Runtime (what the engine enforces)
• Scalar, class/interface, array, callable, Closure, iterable, object, union (|), intersection (&), mixed, never, …
• Violations throw TypeError immediately.
Static / tooling (what Psalm, PHPStan, Phan, IDEs understand)
• Everything above plus pseudo-features: generics (array<int, Foo>), array-shapes (array{status:int, msg:string}), templated classes (Collection<T>), callable signatures (Closure(int):string), etc.
• Purely compile-time hints; nothing changes at runtime.
Keep the separation clear and you’ll rarely be surprised.
- Closure typing cheatsheet
- Declaring a closure with real (runtime-checked) types:
$adder = function (int $a, int $b): int {
return $a + $b;
};
$arrow = fn(float $x): float => $x * 1.08; // PHP 7.4+ arrow functions
- Accepting a closure/callable as a parameter:
function apply(callable $fn, array $list): array
{
return array_map($fn, $list);
}
• callable = string function name, ['Class', 'method'], an object with __invoke, or a real Closure.
• It does not check the callable’s signature – only that it’s invokable.
- Restricting to real closures:
function onlyClosure(Closure $c): void { … } // PHP 8.1+
- Describing the exact signature to static analysers:
/**
* @param Closure(int, int):int $calc two ints → an int
*/
function useCalc(Closure $calc): void { … }
Psalm / PHPStan will now yell if you pass a wrong signature. At runtime nothing changes.
- First-class callable syntax (PHP 8.1+):
strlen(...); // produces Closure(string):int
[$this, 'doStuff'](...); // etc.
- “Array” – generics without generics
PHP proper only knows the monolithic array type, but the ecosystem has collectively agreed on the “phpDoc generic” notation:
array<int, string> // numeric keys, string values
array<string, UserDTO> // map of ids → objects
array{lat:float, lng:float} // fixed-shape (“array shape”)
They work like this:
• You annotate:
/**
* @return array<int, string>
*/
function names(): array
{
return ['Ada', 'Turing'];
}
• Static analyzers catch incorrect returns or bad consumers:
$ints = names(); // Psalm error: expecting string[]
Runtime still sees merely array.
Why bother?
✓ Autocomplete & refactor safety
✓ Prevent silly bugs (mixed soup)
✓ Lets you express intent until true generics arrive (RFCs are in flight).
- Putting both pieces together
Example: a higher-order filter that receives a typed predicate and returns a typed list.
/**
* @template T
* @param array<int, T> $in
* @param Closure(T): bool $predicate
* @return array<int, T>
*/
function filter(array $in, Closure $predicate): array
{
return array_values(array_filter($in, $predicate));
}
// ---- usage ----
$users = filter(
$rawUsers,
fn(User $u): bool => $u->active,
);
• At runtime: only array + Closure are enforced.
• At analysis time: Psalm ties T to User, verifies the predicate signature and the output array element type.
- Recommended mindset / best practices
- Always add real scalar / class types + return types (
int, string, Foo, …).
- Add docblocks for anything the engine can’t express (callable signature, generics, array shape).
- Run Psalm or PHPStan in CI; treat their highest level as “won’t fail the build” quality gate.
- When you need stronger guarantees than
array, reach for value objects (UserCollection, DTOs) or SPL/ArrayObject.
- Watch upcoming RFCs: “generics”, “typed list”, “callable syntax” are active discussions – the gap between runtime and static is closing each release.
Key take-away
Think of PHP typing as two concentric circles:
• Inner circle = runtime; very real, throws TypeError.
• Outer circle = docblock generics/closures; purely static but immensely useful.
Master both, and “closure typing” + “Array types” will stop feeling like black magic and start reading like well-typed pseudocode. Happy hacking!