LanguageMethods, functions and closures

Language

Methods, functions and closures

Methods without the function keyword, implied public, expression bodies, and closures in attributes and defaults, compiled to PER-style PHP.

Phaenon changes how a method is spelled, never what it does. In a class a method is its name and its parameters, title(): string, with no function in front and public unless another visibility is written. A body that is one expression is written => expr;. Functions outside classes keep PHP's function. The compiled PHP has every public function and every block written out, laid out as PER Coding Style 3.0 wants it.

At a glance

you write
namespace App;

abstract class Report
{
    __construct(private string $title) {}

    title(): string => $this->title;

    protected static slug(string $title): string => strtolower(str_replace(' ', '-', $title));

    final path(): string => '/reports/' . static::slug($this->title) . '.html';

    abstract protected body(): string;
}

function headline(Report $report): string => strtoupper($report->title());
phn build writes
<?php

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

declare(strict_types=1);

namespace App;

abstract class Report
{
    public function __construct(private string $title) {}

    public function title(): string
    {
        return $this->title;
    }

    protected static function slug(string $title): string
    {
        return strtolower(str_replace(' ', '-', $title));
    }

    final public function path(): string
    {
        return '/reports/' . static::slug($this->title) . '.html';
    }

    abstract protected function body(): string;
}

function headline(Report $report): string
{
    return strtoupper($report->title());
}

Methods without a keyword

Inside a class, an interface, a trait or an enum, a declaration that starts with a name followed by ( is a method, after any attributes and modifiers. A generic method has its type parameters between the name and the (: first<T>(list<T> $rows): ?T. Anything else is a property or a constant, so a property is declared with a modifier, as in PHP: public string $email, not string $email.

  • No visibility means public, PHP's own rule for a method. public may be written and means the same. The compiled PHP always writes it.
  • Modifiers are PHP's: static, abstract, final, protected, private, in any order PHP accepts. The compiled PHP writes them in PER's order.
  • The constructor is __construct(…), and promotes parameters as in PHP.
  • A class constant without visibility is public, and compiles to public const. A property with private(set) alone is public too, and compiles to public private(set).
  • function stays valid on any method, so PHP code pasted into a .phn compiles. It is required on a method named after a modifier (static, abstract, final, public, protected, private, readonly), var, const, Closure, function or fn, whose bare form would read as something else: public function static(): string. Every other name needs no keyword, PHP's reserved words included, as in list(): list<string>.

phn fmt lifts function off every method that does not need it, and phn migrate does it when it converts a PHP file.

Functions, closures and property hooks

A function outside a class keeps function, and so does a function declared inside a method's body, where process($order) { would read as a call. Everything Phaenon adds to a method, it adds to a function: type parameters, throws, an expression body.

Closures, arrow functions and property hooks are PHP's, unchanged:

namespace App;

final class User
{
    public string $email {
        set(string $value) {
            $this->email = strtolower($value);
        }
    }

    public string $domain {
        get => explode('@', $this->email, 2)[1] ?? '';
    }

    __construct(string $email) {
        $this->email = $email;
    }

    /** @return list<self> */
    static many(string ...$emails): array => array_map(fn (string $e): self => new self($e), array_values($emails));
}

Expression bodies

A function or a method whose body is one expression may write it after an arrow:

You writeIt compiles to
name(): string => $this->name;{ return $this->name; }
log(string $m): void => $this->logger->info($m);{ $this->logger->info($m); }
fail(string $why): never => throw new \LogicException($why);{ throw new \LogicException($why); }

The expression is returned, unless the return type is void or never: then it is only evaluated. The body is checked exactly as the block it stands for would be. An expression body is not allowed on a constructor or a destructor, nor where it would yield, since a generator needs a block (P1004). An abstract or interface method has no body, so it has no arrow either.

A long expression wraps after the arrow, the arrow starting the next line:

load(int $id): Order
    => $this->find($id) ?? throw new \OutOfBoundsException("no order $id");

Closures in attributes and defaults

PHP 8.5 accepts a closure in a constant expression, an attribute argument, a constant or a default value, but only a static function closure: an arrow function is refused there. Phaenon lets you write an arrow function or a function closure without static, and compiles both to the static function PHP accepts:

you write
namespace App;

use Attribute;
use Closure;

#[Attribute]
final class Normalise
{
    __construct(public Closure $fn) {}
}

final class Signup
{
    #[Normalise(fn (string $s): string => strtolower(trim($s)))]
    public string $email = '';

    __construct(private Closure(string): string $slug = fn (string $s): string => strtolower($s)) {}

    slug(string $title): string => ($this->slug)($title);
}
phn build writes
<?php

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

declare(strict_types=1);

namespace App;

use Attribute;
use Closure;

#[Attribute]
final class Normalise
{
    public function __construct(public Closure $fn) {}
}

final class Signup
{
    #[Normalise(static function (string $s): string {
        return strtolower(trim($s));
    })]
    public string $email = '';

    /**
     * @param \Closure(string): string $slug
     */
    public function __construct(private \Closure $slug = static function (string $s): string {
        return strtolower($s);
    }) {}

    public function slug(string $title): string
    {
        return ($this->slug)($title);
    }
}

A closure in a constant expression is static and captures nothing, as PHP requires: $this or a use (…) clause in one is P2531.

Overrides

A method that overrides another is held to the parent's types as PHPStan holds it, on the types you wrote and not only on the PHP types they compile to. list<int> and list<string> are both array to PHP, which links the class, but no caller of the parent can use a child that returns the other:

you write
namespace App;

class Tags
{
    all(): list<string> => [];
}

final class Ids extends Tags
{
    all(): list<int> => [];
}
$ phn checkexit 1
src/Example.phn:10:5: error P2502: return type list<int> of App\Ids::all() is not covariant with App\Tags::all() (list<string>)
   10 |     all(): list<int> => [];
      |     ^^^^^^^^^^^^^^^^^^^^^^^
1 files checked: 1 errors, 0 warnings

A child may still narrow what its parent left open, such as a map<string, mixed> where a PHP parent declares a bare array. When a method implements a generic signature, its parameters compile to the parent's PHP types; see generics.

What the checker reports

CodeWhen
P1001fun before a method, the keyword of the releases before 0.4.0, which phn fmt removes
P1004An expression body on a constructor or destructor, or one that yields
P2202, P2205, P2209An expression body whose value does not match the return type, uses the result of a void call, or returns from a never method
P2502An override whose types are incompatible with the parent's
P2504, P2514A body on an abstract method, or on an interface method
P2516A parameter, return or property without a type
P2531A closure in a constant expression that uses $this or use (…)
you write
namespace App;

final class Counter
{
    const STEP = fn (int $n): int => $n + $this->size;

    private int $size = 0;

    __construct() => $this->size = 1;

    tick(): void => $this->size++;

    next(): int => $this->tick();
}
$ phn checkexit 1
src/Example.phn:5:43: error P2531: a closure in a constant expression cannot use $this
    5 |     const STEP = fn (int $n): int => $n + $this->size;
      |                                           ^^^^^
src/Example.phn:9:19: error P1004: __construct() cannot have an expression body; write a block
    9 |     __construct() => $this->size = 1;
      |                   ^^
src/Example.phn:13:20: error P2205: result of a void function is used
   13 |     next(): int => $this->tick();
      |                    ^^^^^^^^^^^^^
1 files checked: 3 errors, 0 warnings

In the compiled PHP

Each method gets function and, where the source wrote no visibility, public; the modifiers are written in PER's order (final public static function). Expression bodies become blocks with the brace and the return on lines of their own. Closures in constant expressions become static function closures. The output has more lines than the source; the line map at the end of each file lets phn trace and the editors turn a position in the compiled PHP into the .phn line (see line maps and debugging).

Migrating

phn migrate writes the methods of a PHP file without function, and drops a lone public (public function title() becomes title(), final public static function create() becomes final static create()), unless you pass --keep-public. It drops public before a constant and before an asymmetric visibility, and writes a body that is one return (or one expression under void or never) as => expr;, unless --keep-layout. Constructors, destructors and generators keep their blocks.

See also