Language reference

Everything HolyPHP adds on top of PHP — and everything it borrows from Rust. All snippets are verified against the compiler.

echo prints its values together and adds a newline at the end of each statement. Use print when you need output without an automatic newline.

Variables & types

Variables are PHP-style: start with $, no declaration keyword, inferred types. Add an explicit type after the name when you want one.

$count = 5;                  // inferred int
$pi = 3.14159;               // float
$ok = true;                  // bool
$who = "Ada";              // string

$count: int = 5;             // pinned types
$rate: float = 0.19;
$name: string = "Ann";
$flag: bool = false;

$items = [1, 2, 3];          // list array
$user = ["name" => "Ada",  // map array (string keys)
         "lang" => "HolyPHP"];
TypeLiteralsNotes
int42, 0x2A64-bit signed
i128332825110087067562321196029789634457848128-bit signed; wider literals get this type
float3.14, 1e964-bit IEEE
booltrue / false
string"..." with {$var} interpolationimmutable, refcounted
array[1, 2], ["k" => "v"]copy-on-write value semantics
mixedanythingruntime-tagged hval

i128 is a native 128-bit signed integer. It widens from int and the sized integer spellings implicitly, in assignments, arguments, returns and mixed arithmetic (the result stays i128). Narrowing back to int needs an explicit cast; (i128) itself converts from int, float, string and other integers. Arithmetic, comparisons, the spaceship operator, bit operations and shifts all work; / and % are integer division and modulo (unlike int / int, which yields a float), and dividing by zero throws. Overflow wraps like int.

$big = (i128)1 << 100;            // 1267650600228229401496703205376
echo $big * 2;                  // 2535301200456458802993406410752
echo strval($big);              // full decimal value
$back = (i128)"-77";            // from a string
$narrow = (int)$big;            // only an explicit cast narrows

An i128 does not fit into an array, a map, a mixed slot or a closure (those hold a 64-bit runtime value). Storing one there is a compile error rather than a silent truncation: convert with (int) or strval() first. echo, concatenation, templates, strval(), print_r, var_dump and json_encode (as a JSON number) print the full value.

Functions

Fully typed signatures with optional parameters and defaults. Untyped functions are inferred like scripts.

function greet(string $who): string {
    return "Hi, {$who}!";
}

function pow2(float $base, int $exp = 2): float {
    return $base ** $exp;
}

// by-reference parameter (a mutable borrow)
function bump(int &$r): void { $r += 1; }

$n = 41;
bump($n);        // $n === 42

An &$r parameter aliases the caller's variable: the callee writes through it and the call site sees the new value. The argument must be a variable the compiler can alias, and it may live in any of the shapes a variable takes here — a local, a global, a slot a closure captured with use (&$x), or another by-reference parameter.

function anonymize(mixed &$who): void { $who = "nobody"; }

$user = "Elias";
$seen = function() use (&$user): void { anonymize($user); };  // boxed capture
$seen();
echo $user;      // nobody

function total(array &$bag): void { $bag[] = 3; }

$bag = [1, 2];
total($bag);     // $bag === [1, 2, 3]
What is not aliased: a by-reference argument has to be a variable (“bump(1 + 1)” is an error, not a silent copy), a closure cannot declare one (its arguments arrive boxed — capture with use (&$x) instead), and a by-reference parameter cannot itself be captured by reference, since that would need a write-back the compiler does not emit yet. Each of those is a compile error naming the line, never a wrong answer.

Operators

GroupOperators
Arithmetic+ - * / % **
String. concat, .= append
Comparison== != === !== < > <= >= <=>
Logic&& || !
Bitwise& | ^ << >>
Null coalesce??
Compound+= -= *= /= %= .= **=
Increment++ -- (prefix and postfix)
Ternarycond ? a : b

Control flow

if ($n < 2) { return $n; }
elseif ($n == 2) { echo "two"; }
else { echo "many"; }

while ($i < 10) { $i++; }

for ($i = 0; $i < 10; $i++) { echo $i; }

foreach ($nums as $x) { $total += $x; }
foreach ($user as $k => $v) { echo "{$k} => {$v}"; }

match — algebraic switching

function classify(int $n): string {
    return match ($n) {
        0 => "zero",
        1, 2, 3 => "small",
        _ => "big",
    };
}

Classes & OOP

Visibility is explicit: pub (public), private, static for fields. Methods inherit PHP-style; constructors may be inherited too.

class Counter {
    pub int $count = 0;          // field with default
    private $secret = "s";

    pub function __construct(int $start = 0) {
        $this->count = $start;
    }
    pub function bump(): void {
        $this->count += 1;
    }
    pub function get(): int {
        return $this->count;
    }
}

$c = new Counter(10);
$c->bump();
echo $c->get();      // 11
class Animal {
    pub function speak(): string { return "..."; }
}
class Dog extends Animal {
    pub function speak(): string { return "Woof!"; }
}
echo (new Dog())->speak();   // "Woof!" — dynamic dispatch

Closures & captures

Closures capture PHP-style with use. By-value copies by default; use (&$x) captures by reference — the variable lives in a heap box shared with the outer scope.

$base = 100;
$addBase = function(int $x) use ($base): int {   // by value
    return $base + $x;
};

$clicks = 0;
$onClick = function() use (&$clicks): void {     // by reference
    $clicks = $clicks + 1;                       // outer $clicks changes
};
$onClick(); $onClick();
echo $clicks;    // 2
Why it's safe: the compiler boxes the captured variable and forces it to mixed, so the same slot is shared — no dangling pointers, no data races, verified by hphp check.

Exceptions

try {
    throw "boom";
} catch (string $e) {
    echo "caught: {$e}";
} finally {
    echo "always runs";
}

throw accepts a value (strings today, Exception objects too). Handlers are invoked through a setjmp-free architecture — the runtime runs each protected block as a helper, so no volatile tricks appear in generated code and -O2 is safe.

Enums

enum Farbe: int { Rot, Gruen, Blau }

function colorName(Farbe $f): string {
    return match ($f) {
        Farbe::Rot   => "red",
        Farbe::Gruen => "green",
        Farbe::Blau  => "blue",
    };
}

Memory model

HolyPHP checks ownership and supported borrow patterns at compile time. The checker is still a subset of Rust's borrow checker; dynamic values, aliases and unsafe code have additional limits.

ConceptSyntaxMeaning
Value semanticsplain assignmentscalars & arrays copy-on-write
Immutable borrow&$xread-only alias, many allowed
Mutable borrow&mut $xexactly one at a time
Owned boxown<T>exclusive ownership, moves
Shared pointerRc<T>shared ownership syntax backed by the reference-counting runtime
Weak propertypublic weak Node $parent;non-owning nullable reference; reads as Node?
Raw pointer*T / &$x under unsafeonly inside unsafe {}
Memory safety modedeclare(enforce_memory_safety=1);rejects unsafe blocks and calls to builtins marked unsafe
// borrow checker at compile time:
function laenge(string $text): int {     // takes an immutable borrow
    return strlen($text);
}
$w = "borrowed";
echo laenge($w);        // owner keeps $w

// this is a compile ERROR (two mutable borrows):
// function bump(int &$r): void { $r += 1; }
// bump(&$n); bump(&$n); ...  => rejected by hphp check
unsafe {
    $geheim: int = 42;
    $zeiger: &int = &$geheim;      // raw pointer
    echo "deref = " . (*$zeiger);
}
unsafe: raw pointer operations need an unsafe block. The compiler cannot guarantee memory safety for code that uses raw pointers or escapes the supported borrow rules.

Use declare(enforce_memory_safety=1); at the start of a file to make unsafe blocks and calls to builtins marked unsafe compile errors. The declaration applies to the whole file, and the borrow checker analyzes the file's script and functions. Both this mode and ordinary code use the same reference-counted value representation.

Runtime memory: generated owners retain and release strings, arrays, closures, and class instances. Arrays detach on mutation when shared. Strong cycles across objects, arrays, and closures are collected automatically. A weak property does not keep its target alive; it reads as a nullable value and becomes null after collection. See the memory model guide for ownership rules and remaining limits.

Runtime cost: before a program starts a thread, reference counts use a single-thread path and cycle-collector registry operations avoid the mutex. Starting a thread switches those operations to synchronized mode. Generated string-literal sites cache their handle after first use, and owner cleanup registrations reuse a per-thread buffer. In safety mode, parameters used only by read-only builtins such as count(), array_sum(), and strlen(), or forwarded to another proven borrowing parameter, can omit the call-boundary retain/release pair. Unknown calls, writes, returns, stores, methods, and closures keep the normal RC path. A function-local array made from scalar literals also uses a short-lived arena when every use is read-only; returning, storing, or mutating it keeps normal ownership. In canonical counted loops, the same proof can also remove array index checks when the body only passes the stable array to a proven borrower. Safety mode also uses reusable iteration regions for local scalar arrays and strings whose uses stay inside the loop, including method bodies. Calls on concrete class receivers may borrow direct local arguments when every reachable override proves the parameter read-only and nonescaping. Interface or unknown dispatch keeps normal reference counting.

Unsafe pointers: raw addresses are integers outside the managed-object reference-count path. memset() and memcpy() return their input address; stream_recv() copies data out of reusable io_uring buffers before returning an owned string. Builtin temporary cleanup respects borrowed results and immortal string literals.

Indexing: array-list and string reads check their bounds at runtime. An out-of-range read raises a catchable error ("Array index out of bounds" or "String index out of bounds"). Map lookups for absent keys continue to return null. The compiler removes checks in a canonical counted loop when it proves the array and induction variable are stable; in safety mode the body may also pass the array to a proven borrower; other reads retain runtime checks. foreach uses a runtime iterator. array_sum() promotes to a float if adding integer elements would overflow int64.

Threads: captured values and channel payloads move across the thread boundary, so later use of a moved source is a compile error. Immutable scalar and string values may be shared; arrays and maps move when their contents are safe value types and keep copy-on-write behavior. Ordinary mutable objects cannot be sent through channels. Known closures are checked at the boundary, including indirect callbacks typed as thread_callable. The bundled Thread and Pool wrappers use the same checks. See the memory model guide for the proof limits.

Imports & the stdlib

Libraries ship inside the compiler binary — import finds them with no files on disk. A spec without an extension names a library or package; with .hphp it means a file next to the importing source.

import "ui";        // desktop GUI toolkit (embedded)
import "websocket"; // RFC 6455 server (embedded)
import "async";     // event loop + HTTP (embedded)
import "thread";    // OS threads + channels (embedded)
import "helpers";     // helpers.hphp next to this file

Strings

Immutable and refcounted; interpolation is compile-time parsed into concat calls.

$name = "Ada";
echo "Hi {$name}, you have " . (3 + 4) . " new messages";

$s = "Hello";
$s .= " World";          // append (rebuilt behind the scenes)

Arrays & maps

One type for both: lists keep insertion order; assigning a string key or a non-sequential int key promotes to a keyed map (exactly PHP's semantics).

$nums = [5, 3, 8, 1, 9];
$nums[] = 7;                 // append
sort($nums);                 // in place
echo $nums[0];               // 1

$m = [];
$m[1] = "a";                 // key 1 is remembered
$m["name"] = "Ada";        // becomes a keyed map
foreach ($m as $k => $v) {
    echo "{$k} => {$v}";   // 1 => a, then name => Ada
}

$a = [1, 2, 3];
$b = $a;                     // COW: shares until one writes
$b[0] = 99;                  // clones now; $a unchanged