LanguageGenerics

Language

Generics

Type parameters on classes, interfaces, functions and methods, with bounds, defaults and variance, erased to PHP with @template docblocks.

A generic declaration takes types as parameters: a Box<T> holds a T, and first<T>() returns an element of the list it is given. It is what you would write as @template T in a PHPStan docblock, written in the signature instead, and checked by the compiler. The type parameters are erased: the compiled PHP has mixed or the bound where the T stood, and the docblock that PHPStan and PhpStorm read.

At a glance

you write
namespace App;

final class Box<T>
{
    __construct(private T $value) {}

    get(): T => $this->value;

    map<U>(Closure(T): U $fn): Box<U> => new Box($fn($this->value));
}

function first<T>(list<T> $items): ?T => $items[0] ?? null;

function label(): string {
    $box = new Box(42);

    return $box->map(fn (int $n): string => "#$n")->get();
}
phn build writes
<?php

/* @generated by phaenon from Example.phn */

declare(strict_types=1);

namespace App;

/**
 * @template T
 */
final class Box
{
    /**
     * @param T $value
     */
    public function __construct(private mixed $value) {}

    /**
     * @return T
     */
    public function get(): mixed
    {
        return $this->value;
    }

    /**
     * @template U
     * @param \Closure(T): U $fn
     * @return Box<U>
     */
    public function map(\Closure $fn): Box
    {
        return new Box($fn($this->value));
    }
}

/**
 * @template T
 * @param list<T> $items
 * @return ?T
 */
function first(array $items): mixed
{
    return $items[0] ?? null;
}

function label(): string
{
    $box = new Box(42);

    return $box->map(fn (int $n): string => "#$n")->get();
}

new Box(42) is a Box<int>: the checker infers T from the argument, so map() hands the closure an int and returns a Box<string>.

Type parameters

A class, an interface or a trait declares its parameters after its name; a function or a method after its name, before the parentheses. Inside, a parameter is a type like any other.

When a class extends or implements a generic type, it passes the arguments in the clause:

you write
namespace App;

interface Source<T>
{
    next(): ?T;
}

final class Countdown implements Source<int>
{
    __construct(private int $from) {}

    next(): ?int => $this->from > 0 ? $this->from-- : null;
}
phn build writes
<?php

/* @generated by phaenon from Example.phn */

declare(strict_types=1);

namespace App;

/**
 * @template T
 */
interface Source
{
    /**
     * @return ?T
     */
    public function next(): mixed;
}

/**
 * @implements Source<int>
 */
final class Countdown implements Source
{
    public function __construct(private int $from) {}

    public function next(): ?int
    {
        return $this->from > 0 ? $this->from-- : null;
    }
}

implements Source<int> becomes PHP's implements Source and an @implements Source<int> tag, as extends Base<int> becomes @extends Base<int>.

Bounds and defaults

T of Model says that every T is a Model: the members of Model can be used on a T, and a type argument outside the bound is an error (P3002). An unbounded parameter is T of mixed. A default, = string, is the argument used when none is given.

namespace App;

interface Model
{
    id(): int;
}

final class Index<T of Model, K of int|string = int>
{
    private map<K, T> $rows = [];

    put(K $key, T $model): void {
        $this->rows[$key] = $model;
    }

    get(K $key): ?T => $this->rows[$key] ?? null;

    ids(): list<int> => array_values(array_map(fn (Model $m): int => $m->id(), $this->rows));
}

T erases to Model and K to int|string in the compiled signatures, so PHP itself still rejects a value outside the bound.

Variance

A parameter is invariant unless it is marked: out T is covariant (the type only produces T, so a Source<User> is a Source<object>), in T is contravariant (it only consumes T). They are PHPStan's @template-covariant and @template-contravariant.

you write
namespace App;

interface Mapper<in A, out B>
{
    map(A $value): B;
}

final class Length implements Mapper<string, int>
{
    map(string $value): int => strlen($value);
}
phn build writes
<?php

/* @generated by phaenon from Example.phn */

declare(strict_types=1);

namespace App;

/**
 * @template-contravariant A
 * @template-covariant B
 */
interface Mapper
{
    /**
     * @param A $value
     * @return B
     */
    public function map(mixed $value): mixed;
}

/**
 * @implements Mapper<string, int>
 */
final class Length implements Mapper
{
    /**
     * @param string $value
     */
    public function map(mixed $value): int
    {
        return strlen($value);
    }
}

The checker holds the marks to their positions on the members a caller sees (constructors and private members aside): an out T in a parameter, or an in T in a return type, is P3004.

Length::map() shows a rule of the compiled PHP. Its parameter is string in the source and mixed in the PHP, with @param string above it: a method that implements or overrides a generic signature compiles with its parameters widened to the parent's compiled types, because PHP refuses a child whose parameter is narrower than its parent's. The checker still holds callers and the body to string. A return type may narrow in PHP, so int stays.

Closure types

Closure(T): U is the type of a closure that takes a T and returns a U. A parameter marked T= is optional and T... is variadic (last, at most one), as PHPStan writes them: Closure(string, int=): void. A closure type names no parameters, and has no spelling for a parameter by reference. It compiles to \Closure with the signature in the docblock.

Inference and explicit type arguments

The checker infers type arguments from the arguments of a call, then from the closures passed to it, so that $box->map(fn ($n) => …) knows $n is an int without being told. When nothing determines a type argument, write it after the name: new Box<int>(…), first<User>($rows), $box->map<string>(…). A typed property, parameter or return that receives the result also fixes it. Otherwise the checker warns (P3010) and the argument is mixed from there:

you write
namespace App;

function none<T>(): list<T> => [];

function demo(): int {
    $xs = none();

    return count($xs);
}
$ phn checkexit 0
src/Example.phn:6:11: warning P3010: type argument T of App\none() is not inferable here and is mixed: write it as an explicit type argument, or type what receives the result
    6 |     $xs = none();
      |           ^^^^^^
1 files checked: 0 errors, 1 warnings

none<int>() silences it. Explicit arguments are erased like the rest: the compiled call is none().

class<T> and run-time types

A type parameter has no value at run time, so new T(), T::class and $x instanceof T are P3003. When a class needs its T while it runs, it takes the class name as a value, typed class<T>: the type of User::class, a plain string in PHP.

you write
namespace App;

interface Model
{
    id(): int;
}

final class User implements Model
{
    __construct(private int $id) {}

    id(): int => $this->id;
}

final class Repository<T of Model>
{
    __construct(private class<T> $class) {}

    create(int $id): T => new $this->class($id);

    owns(object $o): bool => $o instanceof $this->class;
}

function demo(): User {
    $users = new Repository(User::class);

    return $users->create(7);
}
phn build writes
<?php

/* @generated by phaenon from Example.phn */

declare(strict_types=1);

namespace App;

interface Model
{
    public function id(): int;
}

final class User implements Model
{
    public function __construct(private int $id) {}

    public function id(): int
    {
        return $this->id;
    }
}

/**
 * @template T of Model
 */
final class Repository
{
    /**
     * @param class-string<T> $class
     */
    public function __construct(private string $class) {}

    /**
     * @return T
     */
    public function create(int $id): Model
    {
        return new $this->class($id);
    }

    public function owns(object $o): bool
    {
        return $o instanceof $this->class;
    }
}

function demo(): User
{
    $users = new Repository(User::class);

    return $users->create(7);
}

new $this->class(…) is typed T, and instanceof $this->class narrows to T, so demo() returns a User without a cast. The compiler adds no hidden parameter or property for T: the constructor takes what you wrote, so a dependency injection container wires the class as it wires any other, and a subclass UserRepository extends Repository<User> passes User::class to parent::__construct() itself.

A static property cannot use the class's type parameters (P3008): one slot is shared by every Repository<…>. A static method can.

Generic code from PHP

Phaenon reads PHPStan's generics wherever it reads types: @template, @extends, @implements and @param Repo<User> in the .php files of the project, in vendor code and in PHP's own classes, as PHPStan types them (\ArrayIterator<int, string>, \ReflectionClass<User>, \WeakMap<Key, Value>). A Phaenon class may extend or implement such a class with type arguments, and a docblock @template in a .phn file is still honoured, though the syntax is the way to write a new one.

The compiled PHP goes the other way: a PHP caller sees an ordinary class or function with native types, and PHPStan checks the call from the docblock.

What the checker reports

CodeWhen
P3001A generic type with the wrong number of type arguments: Box<int, string>
P3002A type argument outside its bound: Repository<string>
P3003A type parameter used as a value: new T(), T::class, instanceof T
P3004An out parameter in an input position, or an in parameter in an output position
P3007A property typed with a parent's type parameter, redeclared in a subclass
P3008A class type parameter in a static property
P3009Type arguments on a function or method that has no type parameters
P3010A warning: a type argument nothing determines, read as mixed
you write
namespace App;

interface Model
{
    id(): int;
}

interface Store<out T of Model>
{
    save(T $model): void;
}

function open(Store<string> $store): void {}
$ phn checkexit 1
src/Example.phn:10:10: error P3004: out T cannot be used in parameter $model of save() (an input position)
   10 |     save(T $model): void;
      |          ^^^^^^^^
src/Example.phn:13:21: error P3002: type argument string for T of App\Store is not a subtype of its bound App\Model
   13 | function open(Store<string> $store): void {}
      |                     ^^^^^^
1 files checked: 2 errors, 0 warnings

In the compiled PHP

In the .phnIn the signatureIn the docblock
TmixedT, with @template T
T of ModelModelT, with @template T of Model
out T, in Tas above@template-covariant T, @template-contravariant T
K = stringas above@template K = string
Box<int>BoxBox<int>
Closure(T): U\Closure\Closure(T): U
class<T>stringclass-string<T>
extends Base<int>extends Base@extends Base<int>

A generic declaration gets a docblock with one tag per line, as PHPStan reads them, merged into the docblock the source already has. Explicit type arguments at a call are removed. Nothing remains of the generics at run time, and nothing is checked there that PHP does not check itself.

Migrating

phn migrate lifts PHPStan's generics into the syntax where the result compiles back to the signature PHP already had: @template T of Foo becomes <T of Foo>, @extends Base<T> becomes extends Base<T>, @param list<T> $xs becomes list<T> $xs, @return T becomes : T, and class-string<T> becomes class<T>. This PHP:

/**
 * @template T
 * @implements \IteratorAggregate<int, T>
 */
final class Collection implements \IteratorAggregate
{
    /**
     * @param list<T> $items
     */
    public function __construct(private array $items)
    {
    }

    /**
     * @template U
     * @param \Closure(T): U $fn
     * @return Collection<U>
     */
    public function map(\Closure $fn): Collection
    {
        return new Collection(array_map($fn, $this->items));
    }

    /**
     * @return \ArrayIterator<int, T>
     */
    public function getIterator(): \ArrayIterator
    {
        return new \ArrayIterator($this->items);
    }
}

becomes this .phn:

namespace App;

final class Collection<T> implements \IteratorAggregate<int, T>
{
    __construct(private list<T> $items) {}

    map<U>(Closure(T): U $fn): Collection<U> => new Collection(array_map($fn, $this->items));

    getIterator(): \ArrayIterator<int, T> => new \ArrayIterator($this->items);
}

A tag whose type has no Phaenon spelling stays in the docblock, and migrate says why.

See also