Language
Named shapes and type aliases
type declarations name a type once for a whole namespace; a named shape describes an array with known keys, erased to an array{…} docblock.
A type declaration gives a type a name: type Ids = list<int>;. Its most common use is a
named shape, the type of an array whose keys are known, such as a row from a database or a
decoded payload: type Row = array{id: int, name?: string};. A shape is what PHPStan writes as
array{…} in a docblock; in Phaenon it is written once, under a name, and used in signatures
like a class name. It is a static type only: the compiled PHP has array in the signature and
the shape in the docblock.
At a glance
namespace App;
type Row = array{id: int, name?: string};
function label(Row $row): string => ($row['name'] ?? 'nobody') . ' #' . $row['id'];
function row(int $id): Row => ['id' => $id];<?php
/* @generated by phaenon from Example.phn */
declare(strict_types=1);
namespace App;
/**
* @param array{id: int, name?: string} $row
*/
function label(array $row): string
{
return ($row['name'] ?? 'nobody') . ' #' . $row['id'];
}
/**
* @return array{id: int, name?: string}
*/
function row(int $id): array
{
return ['id' => $id];
}Writing a shape
A shape lists its entries, each a key, a colon and a type:
- a key is a name (
id, and PHP's reserved words too, such asclass), a quoted string for a key that is not a name ('a-b','$set'), or an integer (0,-1); ?after a key makes the entry optional:name?: stringmay be absent, whilename: ?stringis always present and may benull;- an entry's type is any type, another shape included, so shapes nest;
...as the last entry leaves the shape unsealed: it may hold keys it does not name.
namespace App;
final class Customer
{
__construct(public string $name) {}
}
type Line = array{sku: string, quantity: int};
type Order = array{
id: int,
buyer: ?Customer,
lines: list<Line>,
meta: array{source: string, ...},
};
function quantity(Order $order): int {
$total = 0;
foreach ($order['lines'] as $line) {
$total += $line['quantity'];
}
return $total;
}A shape is structural: Row and a docblock's array{id: int, name?: string} are the same type,
and two aliases with the same right-hand side are interchangeable. A positional shape is a
tuple, (string, int), written as one (see tuples).
Only in a type declaration
array{…} is written on the right-hand side of a type declaration and nowhere else. In a
parameter, a return type or a property, it is a syntax error that says to name it:
namespace App;
function id(array{id: int} $row): int => $row['id'];src/Example.phn:3:1: error P1000:
1 files checked: 1 errors, 0 warningsThe rule keeps signatures short and gives a shape one place to change. It also keeps the syntax
readable by every tool: ): array { is where a function body starts, and only after
type Name = can a brace be nothing but a shape.
Aliases belong to their namespace
A type alias is declared in a namespace as a class is, and any file of the project finds it.
Files of another namespace import it with use, as they would a class:
namespace App\Orders;
type Line = array{sku: string, quantity: int};
type Order = array{id: int, lines: list<Line>, note?: string};<?php
/* @generated by phaenon from Types.phn */
declare(strict_types=1);
namespace App\Orders;namespace App\Orders;
final class Orders
{
private map<int, Order> $rows = [];
add(Order $order): void {
$this->rows[$order['id']] = $order;
}
find(int $id): ?Order => $this->rows[$id] ?? null;
}<?php
/* @generated by phaenon from Orders.phn */
declare(strict_types=1);
namespace App\Orders;
final class Orders
{
/**
* @var array<int, array{id: int, lines: list<array{sku: string, quantity: int}>, note?: string}>
*/
private array $rows = [];
/**
* @param array{id: int, lines: list<array{sku: string, quantity: int}>, note?: string} $order
*/
public function add(array $order): void
{
$this->rows[$order['id']] = $order;
}
/**
* @return ?array{id: int, lines: list<array{sku: string, quantity: int}>, note?: string}
*/
public function find(int $id): ?array
{
return $this->rows[$id] ?? null;
}
}namespace App\Http;
use App\Orders\Order;
function lineCount(Order $order): int => count($order['lines']);The file that holds only type declarations still compiles to a .php, with nothing in it but
the header and the namespace. An alias has no run-time existence: new Row(), Row::class and
instanceof Row are P2001, whose message says that Row is a type alias. Since the compiled
PHP carries the expanded shapes and never the name, a library's aliases are visible to the
projects that read its .phn sources, and to nobody else.
Generic aliases
An alias takes type parameters like a class:
namespace App;
type Page<T> = array{items: list<T>, total: int, next?: string};
final class User
{
__construct(public string $email) {}
}
function first<T>(Page<T> $page): ?T => $page['items'][0] ?? null;
function firstEmail(Page<User> $page): ?string => first($page)?->email;first($page) with a Page<User> returns a ?User: the type argument is inferred through the
shape, entry by entry.
Which arrays are a shape
A value is accepted where a shape is expected when it has every required key with a value of the entry's type. The rules are PHPStan's:
- an array literal with those keys is accepted, and so is one with more keys; one that lacks a required key, or has a value of the wrong type, is not;
- a general array, a
map<string, int>or anarray<mixed>, is not a shape with a required key, since it may lack the key. It is accepted only where every entry is optional and its values fit; - reading a key that a sealed shape does not name is
P2313; - an optional entry is read with a fallback,
$row['name'] ?? 'nobody', or afterisset()orarray_key_exists(). Read without one, it isP2321, "might not exist", and so is a key an unsealed shape does not name, whose value ismixed.
namespace App;
type Row = array{id: int, name?: string};
function fromMap(map<string, int> $values): Row => $values;
function fromLiteral(): Row => ['name' => 'Ada'];
function age(Row $row): mixed => $row['age'];
function name(Row $row): string => $row['name'];src/Example.phn:5:52: error P2202:
5 | function fromMap(map<string, int> $values): Row => $values;
| ^^^^^^^
src/Example.phn:7:32: error P2202:
7 | function fromLiteral(): Row => ['name' => 'Ada'];
| ^^^^^^^^^^^^^^^^^
src/Example.phn:9:39: error P2313:
9 | function age(Row $row): mixed => $row['age'];
| ^^^^^
src/Example.phn:11:41: error P2321:
11 | function name(Row $row): string => $row['name'];
| ^^^^^^
1 files checked: 4 errors, 0 warningsA test of the key narrows the shape itself, so what it proved holds for the rest of the
function, through a write to another key or a copy, until the key is unset():
namespace App;
type Row = array{id: int, name?: string};
function label(Row $row): string {
if (!isset($row['name'])) {
return 'nobody';
}
$row['id'] = 0;
return $row['name'];
}Nothing is checked at run time. A decoded payload is an array<mixed>, and becomes a Row once
your code tests it, or a guard function with @phpstan-assert says so (see type tests and
narrowing).
A shape or a class
A class is right when the data has behaviour, invariants or an identity, or when it crosses many
layers: a constructor can validate it, PHP checks its property types at run time, and an IDE
renames its fields. A shape is right for the arrays PHP code already passes around: rows from a
database driver, configuration, payloads before they become objects, the options of a function.
A recursive structure is a class: an alias that mentions itself is P2015.
Shapes in docblocks
A shape nobody named stays in a docblock, as PHPStan writes it, in .phn and .php alike:
@param array{id: int, tags: list<string>} $row above an array $row parameter. A
docblock shape may name an alias (@return array{total: int, rows: list<Row>}), and the compiler
expands it for PHPStan. The @phpstan-type and @phpstan-import-type tags of PHP code are read
as PHPStan reads them.
What the checker reports
| Code | When |
|---|---|
P1000 | array{…} outside a type declaration (a syntax error) |
P2001 | An alias used as a class: new Row(), Row::class, instanceof Row |
P2015 | An alias that mentions itself, directly or through another alias |
P2511 | A name declared twice in a namespace (two aliases, or an alias and a class, interface, enum or trait), or a shape key written twice |
P2103, P2201, P2202 | A value that is not the shape, passed, assigned or returned |
P2313 | A key a sealed shape does not name |
P2321 | An optional entry, or a key an unsealed shape does not name, read without a test |
namespace App;
final class Row
{
}
type Row = array{id: int};
type Tree = array{value: int, children: list<Tree>};src/Example.phn:7:6: error P2511:
7 | type Row = array{id: int};
| ^^^
src/Example.phn:9:6: error P2015:
9 | type Tree = array{value: int, children: list<Tree>};
| ^^^^
1 files checked: 2 errors, 0 warningsIn the compiled PHP
The type declaration leaves nothing in the output. Every signature that names an alias gets
the erased type, array for a shape, and its docblock gets the alias expanded in full, with
class names fully qualified, so PHPStan reads the same type without a @phpstan-type tag. The
compiled PHP repeats the shape wherever it is used; the source is where it is written once.
Migrating
phn migrate lifts @phpstan-type and @psalm-type tags into type declarations of the
class's namespace, and @phpstan-import-type into use. This PHP:
/**
* @phpstan-type Line array{sku: string, quantity: int}
*/
final class Orders
{
/**
* @return Line
*/
public function line(string $sku): array
{
return ['sku' => $sku, 'quantity' => 1];
}
}becomes:
namespace App;
type Line = array{sku: string, quantity: int};
final class Orders
{
line(string $sku): Line => ['sku' => $sku, 'quantity' => 1];
}An alias whose name is already taken in the namespace stays a tag, with a note, since PHPStan's
aliases belong to a class and two classes may each have a Row. A shape written inline in a
@param or @return stays a docblock: the tool cannot invent a name for it.