LanguagePhaenon for PHP developers

Language

Phaenon for PHP developers

A tour of Phaenon for PHP developers: what stays PHP, what the language adds, what it refuses, and what the compiled PHP looks like.

Phaenon is PHP 8.5 with types PHP cannot write and a checker that reads them. A .phn file is PHP without the <?php tag, plus generics, typed lists and maps, tuples, named shapes, a bytes type, throws clauses and a shorter way to declare methods. The compiler checks it and writes the PHP you would have written by hand: native types where PHP has them, PHPStan docblocks where it does not, and nothing else. This page is a tour; each section links to the page that covers its subject.

At a glance

you write
namespace App;

final class UnknownUser extends \RuntimeException {}

final class User
{
    __construct(public int $id, public string $email) {}
}

final class Users
{
    private map<int, User> $byId = [];

    add(User $user): void {
        $this->byId[$user->id] = $user;
    }

    get(int $id): User throws UnknownUser => $this->byId[$id] ?? throw new UnknownUser("no user $id");

    emails(): list<string> => $this->byId
        |> array_map(fn (User $u): string => $u->email, ?)
        |> array_values(...);
}
phn build writes
<?php

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

declare(strict_types=1);

namespace App;

final class UnknownUser extends \RuntimeException {}

final class User
{
    public function __construct(public int $id, public string $email) {}
}

final class Users
{
    /**
     * @var array<int, User>
     */
    private array $byId = [];

    public function add(User $user): void
    {
        $this->byId[$user->id] = $user;
    }

    /**
     * @throws UnknownUser
     */
    public function get(int $id): User
    {
        return $this->byId[$id] ?? throw new UnknownUser("no user $id");
    }

    /**
     * @return list<string>
     */
    public function emails(): array
    {
        return array_values(array_map(fn (User $u): string => $u->email, $this->byId));
    }
}

What stays PHP

Everything that runs. Phaenon adds types and the spelling of declarations, and never an operation or a run-time behaviour PHP lacks:

  • The runtime is PHP's. The compiled code runs on PHP 8.5 or 8.6 with nothing installed beside it: no runtime library, no extension, no Composer package.
  • Evaluation is PHP's. Order of evaluation, copy-on-write arrays, references, integer and float behaviour, == and ===, exceptions: a line of a .phn file does what the same line does in PHP.
  • Every PHP 8.5 feature is there: classes, interfaces, traits, enums, readonly properties, property hooks, asymmetric visibility, attributes, closures and arrow functions, match, named arguments, union, intersection and DNF types, generators, fibers, clone with, and the |> operator. PHP 8.6's partial application is accepted too, and lowered for an 8.5 target (see pipes and partial application).
  • Type tests are PHP's: is_int($x), $x instanceof User, array_is_list($x). The checker narrows through them (see type tests and narrowing).

declare(strict_types=1) is implied: the compiler writes it into every file.

What Phaenon adds

FeatureExamplePage
Genericsfinal class Box<T>, first<T>(list<T> $xs): ?TGenerics
Lists, maps, tupleslist<User>, map<string, int>, (string, int)Lists, maps and tuples
Named shapes and aliasestype Row = array{id: int, name?: string};Named shapes and type aliases
Binary databytes, (bytes) $rawText and bytes
Methods without a keywordtitle(): string => $this->title;Methods, functions and closures
Closures in attributes and defaults#[Normalise(fn (string $s): string => trim($s))]Methods, functions and closures
Exception clauseswithdraw(int $n): void throws InsufficientFunds, nothrowthrows and nothrow
class<T>__construct(private class<T> $class)Generics

Each of these is a type or a spelling. A type is erased: list<User> is array in the compiled signature and list<User> in its docblock, and nothing checks it at run time that PHP does not check itself. A spelling is a keyword or a brace away from the PHP the compiler writes: title(): string => $this->title; is public function title(): string { return $this->title; }.

What Phaenon refuses

A short list of PHP constructs is a compile error in a .phn file: the <?php tag and inline HTML, global, goto, eval(), extract() and compact(), variable variables, the alternative syntax, var, list(), tabs, and declarations without a type. Each has a direct replacement. PHP files in the same project may still use them. See what Phaenon refuses.

The checker

The type checker is the reason for the language. phn check reads the whole program and reports what PHPStan reports at level max: it may be stricter than PHPStan, and is meant never to be more lenient. Each finding has a stable code, P2103 for an argument of the wrong type, and points at the .phn line:

you write
namespace App;

function total(list<int> $amounts): int => array_sum($amounts);

function demo(): int => total(['10', '20']);
$ phn checkexit 1
src/Example.phn:5:31: error P2103: argument 1 ($amounts) of App\total() expects list<int>, list{'10', '20'} given
    5 | function demo(): int => total(['10', '20']);
      |                               ^^^^^^^^^^^^
1 files checked: 1 errors, 0 warnings

See the type checker for the codes, the output formats and the warnings.

The compiled PHP

One .phn file compiles to one .php file with the same namespace, classes and functions. A project's source root compiles into a sibling directory, src/ into .src/, where Composer's autoloader, PHPUnit and PHPStan read it (see phaenon.json). The compiler adds:

  • a header naming the source, and declare(strict_types=1);
  • the docblocks that carry the types PHP cannot write, in PHPStan's vocabulary;
  • public function before each method, and blocks for expression bodies, laid out as PER Coding Style 3.0 wants them;
  • the PHP that a construct newer than the target lowers to;
  • a last line, the line map, which the tools read to turn a compiled position into a .phn one (see line maps and debugging).

It adds no identifier you did not write: no hidden parameter, no generated member, no renamed variable, no call into a package. A file with a type error is not written, so the compiled tree is always one that passed the checker. PHPStan at level max reads the same types in it, and a PHP caller sees an ordinary class with native types and docblocks.

Reading PHP code

Phaenon code calls PHP code, and PHP code calls Phaenon code without knowing. The checker reads the types of everything the program uses:

  • PHP's own functions and classes from the php-src stubs built into phn, with PHPStan's refinements: array_map() keeps a list a list, explode() returns a non-empty list.
  • Vendor packages through Composer's autoload maps, read from vendor/composer: native types and PHPStan docblocks (@param, @return, @var, @template, @extends, @phpstan-assert, array shapes), as PHPStan reads them.
  • The project's own .php files, the same way, so a project moves to Phaenon one file at a time.

A docblock is the interop contract in both directions: what a PHP library documents is what the checker holds a .phn caller to, and what a .phn file declares reaches PHP callers as a docblock.

See also