Declarations and registration

Argument parsing and return values

Functions, methods and closures use the same typed handler signatures. Declare arguments and the return type in Zig and use a trailing phpz.Variadic for variadic arguments. Use Ctx or GuardCtx to parse arguments manually if you need constraints on referenced values, specific classes or a type-checked zval view. Keep either signature consistent with the PHP stub.

Arguments and return values

The following handler implements function greet(string $name): string. For binding details, see Function bindings.

pub fn greet(name: []const u8) []const u8 {
    return name;
}

The wrapper checks arguments before calling the handler and sets the PHP return value on success. The input slice borrows the argument’s bytes. The wrapper copies the returned slice. The equivalent explicit specification is:

pub fn greet(ctx: phpz.Ctx) !void {
    const args = try ctx.call.expectArgs(&.{
        .{ .string = .{} },
    }, {});
    ctx.ret(.string, args[0]);
}

expectArgs derives the argument count from the specification and returns a typed tuple. Scalar arguments follow Zend parameter parsing (ZPP) conversion rules, just as they do in typed signatures. See Optional and nullable arguments.

ctx.call.arg(1) borrows the first argument. With this low-level interface, check the count and type before accessing the value.

Both Ctx and GuardCtx provide ctx.ret(kind, value), shorthand for ctx.retval.set(kind, value). It accepts the same types as Ownership and reference counting. ctx.retval is a *phpz.Zval pointing to the PHP return slot. Use ctx.retval.ptr() with lower-level APIs.

ret writes the return slot and execution continues. Use return ctx.ret(.int, 42); to exit the Zig function immediately.

Typed handler signatures

An optional Ctx or GuardCtx precedes all PHP arguments. For ordinary instance methods on a class with Zig fields, self comes first. A context-only handler checks its own arguments. For typed arguments the wrapper parses the entire signature and rejects excess arguments unless it ends in Variadic.

Zig parameterPHP declarationInput and behavior
i8 / i16 / i32 / i64 / isizeint $aParse a PHP int and check the Zig range. Overflow raises an argument ValueError
u8 / u16 / u32 / u64 / usizeint $aParse a PHP int and check the Zig range. Negative or out-of-range values raise an argument ValueError
f32 / f64float $aParse a PHP float. Conversion to f32 checks finite values for overflow and can lose precision
boolbool $aParse a PHP bool
[]const u8string $aParse a PHP string and borrow its bytes
[:0]const u8string $aBorrow a NUL-terminated slice, preserving the length and embedded NULs
*phpz.zend.Stringstring $aParse a PHP string and borrow the Zend string
*phpz.zend.Arrayarray $aBorrow the PHP array
*phpz.zend.Objectobject $aBorrow the PHP object
*phpz.zend.Resource@param resource $a (PHPDoc)Borrow the PHP resource
*phpz.Stream@param resource $a (PHPDoc)Check for a regular or persistent stream resource and borrow the stream
*phpz.zend.Callablecallable $aResolve the callable. The temporary resolution is valid only during this invocation
*phpz.zend.Referencemixed &$aBorrow the PHP reference. Use a manual .reference.kind to constrain the referenced value
*phpz.Zvalmixed $aBorrow the argument zval, accepting any PHP value including null
phpz.Mixed(&.{ .int, .string })int|string $aParse into a tagged union
?Tint $a = 0The argument may be omitted. The outer null means it was absent
phpz.Nullable(T)?int $a / int|null $aAccept explicit PHP null, represented by .null or otherwise by .value
?phpz.Nullable(T)?int $a = nullAccept omission and explicit null
phpz.Variadicmixed ...$aMust come last. Borrows remaining positional and extra named arguments and validates entries on demand

The three T rows illustrate Zig i64 and PHP int. A Zig ?T permits omission. To accept explicit PHP null, choose a type that supports it. Handle stub defaults in the Zig implementation. A variadic declaration can constrain its elements, for example int ...$a. Check each with Entry.expect().

PHP has no native resource parameter type. Document it in the stub with @param resource, as in Borrowing a PHP stream.

Nullable(T) supports scalars, strings, arrays, objects, resources, *phpz.Stream and *phpz.zend.Callable. *Zval already accepts null, and Mixed can include .null. Use a manual specification to constrain the value inside a reference.

Scalar parsing follows these rules:

  • In weak mode, ZPP supports conversions such as "12" to int, 1 to float and a Stringable object to string. Failed conversions raise TypeError.
  • With declare(strict_types=1) in the caller, int to float remains valid. The other weak conversions above are rejected.
  • Conversion updates the argument in the current call frame, including the value you see with as = .zval. Arrays, objects, resources, reference constraints and Mixed unions do not use scalar coercion.
  • Non-nullable scalars follow the target PHP version’s null handling. In PHP 8.2–8.6, weak calls emit a deprecation before conversion and strict calls reject null. Use Nullable(T) or nullable = true to preserve null.

?T makes an argument optional. If T itself accepts null, as mixed or a union containing .null does, it still accepts PHP null. Put optional arguments after required arguments.

Omitted and null arguments

For example, the following handler implements function choose(?int $value = null): ?int:

pub fn choose(value: ?phpz.Nullable(i64)) phpz.Nullable(i64) {
    return value orelse .{ .value = 0 };
}
var_dump(choose());     // int(0)
var_dump(choose(null)); // NULL
var_dump(choose(42));   // int(42)

The outer ? tells the handler whether the argument slot was supplied. For a supplied slot the inner Nullable(i64) carries either .null or .value. Here orelse runs only for the omitted argument. For calls that skip an earlier parameter by name, see Named and variadic arguments.

Typed unions

const IntOrString = phpz.Mixed(&.{ .int, .string });

pub fn describe(value: IntOrString) []const u8 {
    return switch (value) {
        .int => "integer",
        .string => "string",
    };
}

The matching PHP declaration is function describe(int|string $value): string. Mixed requires at least two distinct types. It can include .null and excludes .mixed, .reference and .callable. Use phpz.Mixed. A hand-written Zig union with similar fields is a different signature type.

Direct returns and ownership

Supported return types include the integers and floats listed above, bools, byte slices, pointers to Zend strings, arrays, objects and resources, *zend.Reference, *Zval, Mixed, Nullable(T), optionals and their error unions. Variadic is input-only. With void or !void, use ctx.ret() to write a result. For other types let the wrapper set the PHP result from the Zig return value.

  • Integers must fit in zend_long or conversion returns ReturnValueOutOfRange.
  • The wrapper copies byte slices after the handler returns. Never return a slice of a stack buffer or memory released by defer. For local bytes, copy them inside the handler with String.init or call ctx.ret(.string, bytes) before returning.
  • A returned *zend.String, *zend.Array, *zend.Object, *zend.Resource or *zend.Reference transfers one reference. Before returning a borrowed pointer, copy or retain it as described in Ownership and reference counting.
  • Returning *Zval copies the dereferenced value. Its source retains ownership and must still be valid when the wrapper reads it.
  • *Stream and *zend.Callable cannot be returned directly. To transfer a stream, call toZval(ctx.retval).
  • For direct returns, a PHP by-reference declaration (function &name()) requires *zend.Reference or its error union. A by-value declaration cannot return a reference directly. A context handler returning void or !void writes the return slot itself and must honor the declared reference semantics.

Returning a borrowed union value

The active tag determines what PHP takes ownership of. In this example the handler retains a mutable array, object or resource for the return slot. An immutable array needs no increment. phpz copies the bytes of a string and writes scalar values directly.

function keepValue(mixed $value): mixed {}
const Value = phpz.Mixed(&.{ .null, .bool, .int, .float, .string, .array, .object, .resource });

pub fn keepValue(value: Value) Value {
    switch (value) {
        .array => |array| if (!array.isImmutable()) array.addref(),
        inline .object, .resource => |ptr| ptr.addref(),
        else => {},
    }
    return value;
}
$original = (object) ["name" => "phpz"];
$result = keepValue($original);
unset($original);
echo $result->name; // phpz

Manual parsing

Use a context handler for instanceof checks, reference write-back, raw zvals or custom argument counts. expectArgs returns a typed tuple. The lower-level parseArgs uses PHP format strings and the corresponding conversion and output-pointer conventions.

Compile-time and Debug declaration checks

At compile time phpz compares typed handlers with arginfo for required and fixed parameter counts, variadic and parameter reference flags, and the reference flag on direct returns. A mismatch causes a compile error identifying the function or method. Keep PHP types and defaults in sync through stub regeneration and PHPT coverage. For context-only handlers, Zig Debug builds check the required and fixed counts and variadic flag against the current function’s arginfo before each expectArgs. A mismatch terminates the process with a Zig panic reporting expectArgs declaration mismatch.

The runtime check excludes parameter types and defaults. ReleaseSafe, ReleaseFast and ReleaseSmall skip it regardless of the PHP build mode. Closures created by phpz with generic arginfo skip it as well. Closures derived from a registered function with its original declaration are checked. To parse a subset, use expectArgCount and expectArg and check all counts, types and extra named arguments yourself. For fixed by-reference parameters use *zend.Reference, its optional form, or raw *Zval. Direct returns follow the reference rules above.

Argument parsing types

The first argument to expectArgs is an array of ExpectArgKind.Spec. The second supplies runtime data for specifications such as callable or object instanceof. Common options include:

OptionApplies toMeaning
optional = trueAll except .null and .variadicAllows omission and wraps the result in ?T
nullable = trueScalars, arrays, objects, resources and callablesAccepts explicit null and returns phpz.Nullable(T) unless as = .zval is selected
as = .zval.int, .float, .bool, .string, .array, .object, .resourceReturns the borrowed *Zval

Optional arguments must follow required ones. .null cannot stand alone as a parameter specification. Use optional + nullable or .mixed to distinguish omission, explicit null and a supplied value. as selects the output type. Numeric range checks match those for typed handlers.

These seven types support optional, nullable and as:

SpecificationDefault Zig resultOwnership
.inti64Scalar value
.floatf64Scalar value
.boolboolScalar value
.string[]const u8Borrowed byte slice
.array*zend.ArrayBorrowed array
.object*zend.ObjectBorrowed object
.resource*zend.ResourceBorrowed resource

For a default result type T, combine options as follows:

OptionsZig resultExplicit null
DefaultTNon-nullable scalars follow ZPP as above. Other types reject null
optional?TSame as the default. Outer null means omission
nullablephpz.Nullable(T).null for PHP null, .value otherwise
optional + nullable?phpz.Nullable(T)Outer null means omission. Inner .null means PHP null
as = .zval*ZvalNon-nullable scalars follow ZPP as above. Other types reject null
nullable + as = .zval*ZvalCall is(.null) on the borrowed zval
optional + as = .zval, optionally with nullable?*ZvalOuter null means omission. Add nullable to preserve PHP null. Otherwise the rules above apply

as = .zval takes precedence when selecting the result type and skips the Nullable(T) wrapper. The specification still checks the underlying type.

Each row below pairs one PHP declaration with the specification for its first argument. The last column is the Zig value read from args[0].

.int

PHP stub signatureZig specification in expectArgsType of args[0]
function takeInt(int $n): void.{ .int = .{} }i64
function byteValue(int $n): int.{ .int = .{ .as = .u8 } }u8
function optionalInt(int $n = 0): void.{ .int = .{ .optional = true } }?i64
function nullableInt(?int $n): void.{ .int = .{ .nullable = true } }phpz.Nullable(i64)
function optionalNullableInt(?int $n = null): void.{ .int = .{ .optional = true, .nullable = true } }?phpz.Nullable(i64)
function inspectInt(?int $n): void.{ .int = .{ .nullable = true, .as = .zval } }*Zval
pub fn byteValue(ctx: phpz.Ctx) !u8 {
    const args = try ctx.call.expectArgs(&.{.{ .int = .{ .as = .u8 } }}, {});
    return args[0];
}
var_dump(byteValue(255)); // int(255)
optionalInt();
nullableInt(null);
optionalNullableInt();
optionalNullableInt(null);

Both takeInt and byteValue declare PHP int. The .u8 specification additionally checks the range 0–255. Calling byteValue(256) raises ValueError. The stub default in optionalInt is metadata: the handler supplies zero with args[0] orelse 0 when the slot is absent.

.float

PHP stub signatureZig specification in expectArgsType of args[0]
function takeFloat(float $n): void.{ .float = .{} }f64
function takeFloat32(float $n): void.{ .float = .{ .as = .f32 } }f32
takeFloat(3);
takeFloat32(1.25);

.float = .{} reads f64 and .float = .{ .as = .f32 } reads f32. Both accept PHP ints. Weak calls also accept other ZPP-convertible scalars. The f32 range check runs after conversion. Options combine as shown above.

.bool

PHP stub signatureZig specification in expectArgsType of args[0]
function takeFlag(bool $flag): void.{ .bool = .{} }bool
takeFlag(false);

.bool = .{} returns a Zig bool. Weak calls use ZPP scalar conversions. Strict calls accept only PHP true and false. Arrays and other non-scalars are rejected.

.string

PHP stub signatureZig specification in expectArgsType of args[0]
function takeBytes(string $s): void.{ .string = .{} }[]const u8
function takeZendString(string $s): void.{ .string = .{ .as = .str } }*zend.String
function takeCString(string $s): void.{ .string = .{ .as = .cstr } }[:0]const u8
takeBytes("a\0b");
takeZendString("phpz");
takeCString("a\0b");

.string = .{} borrows a []const u8 of arbitrary bytes with no UTF-8 guarantee. .string = .{ .as = .str } borrows a *zend.String. To keep either past the source value’s lifetime, see Strings.

.string = .{ .as = .cstr } borrows a [:0]const u8, just like the corresponding typed parameter. It supports optional and nullable without allocating or retaining the string. The slice preserves embedded NULs. A C string function passed its .ptr sees only bytes before the first NUL.

.array

PHP stub signatureZig specification in expectArgsType of args[0]
function takeArray(array $items): void.{ .array = .{} }*zend.Array
function inspectArray(array $items): void.{ .array = .{ .as = .zval } }*Zval
takeArray([10, 20]);
inspectArray(["count" => 2]);

.array = .{} borrows a *zend.Array. .array = .{ .as = .zval } borrows a *Zval from which array() obtains a Zval.Array view. Neither separates shared arrays automatically. See Arrays before modifying one.

.object

PHP stub signatureZig specification in expectArgsType of args[0]
function takeObject(object $obj): void.{ .object = .{} }*zend.Object
function takeUser(User $user): void.{ .object = .{ .instanceof = true } }*zend.Object
takeObject(new stdClass());
takeUser(new User());

Use instanceof = true to require a class or interface. Supply its class entry at the matching position in the runtime tuple:

const args = try ctx.call.expectArgs(&.{
    .{ .object = .{ .instanceof = true } },
}, .{
    .{ .class = UserClass.entry },
});

const user: *phpz.zend.Object = args[0];

Use {} when a specification needs no runtime data. For an int followed by an object, pass .{ {}, .{ .class = UserClass.entry } }.

.resource

PHP stub signatureZig specification in expectArgsType of args[0]
/** @param resource $r */ function takeResource($r): void.{ .resource = .{} }*zend.Resource
/** @param resource $r */ function takeStream($r): void.{ .resource = .{ .as = .stream } }*phpz.Stream
$stream = fopen("php://memory", "w+");
takeResource($stream);
takeStream($stream);
fclose($stream);

.resource = .{} borrows a *zend.Resource and checks only the PHP resource kind. .resource = .{ .as = .stream } checks for a regular or persistent PHP stream and borrows a *phpz.Stream (see PHP streams). For a custom payload, use its Resource.Typed(...).fetch() to verify the type and that the resource is open. See PHP resources.

.reference

PHP stub signatureZig specification in expectArgsType of args[0]
function takeRef(mixed &$v): void.{ .reference = .{} }*zend.Reference
function optionalRef(mixed &$v = null): void.{ .reference = .{ .optional = true } }?*zend.Reference
function inspectIntRef(int &$v): void.{ .reference = .{ .kind = .int, .as = .value } }*Zval
function inspectRef(mixed &$v): void.{ .reference = .{ .as = .zval } }*Zval
$n = 7;
inspectIntRef($n);
optionalRef();

With .as = .value the zval points to the referenced value. With .as = .zval it points to the outer reference. Pass a PHP variable when supplying a by-reference argument.

.mixed

PHP stub signatureZig specification in expectArgsType of args[0]
function takeMixed(mixed $v): void.{ .mixed = .{} }*Zval
function optionalMixed(mixed $v = null): void.{ .mixed = .{ .optional = true } }?*Zval
function takeUnion(int|string $v): void.{ .mixed = .{ .one_of = &.{ .int, .string } } }Union
function optionalUnion(int|string $v = 0): void.{ .mixed = .{ .optional = true, .one_of = &.{ .int, .string } } }?Union
takeMixed(null);
takeUnion(42);
takeUnion("phpz");
optionalUnion();

Union here is phpz.Mixed(&.{ .int, .string }). Switch on .int or .string to use the payload. An optional union can also be omitted. The tags .mixed, .reference, .callable and .variadic cannot be members of one_of.

.callable

PHP stub signatureZig specification in expectArgsType of args[0]
function takeCallback(callable $cb): void.{ .callable = .{} }*Zval
function optionalCallback(callable $cb = UNKNOWN): void.{ .callable = .{ .optional = true } }?*Zval
function nullableCallback(?callable $cb): void.{ .callable = .{ .nullable = true } }phpz.Nullable(*Zval)
function optionalNullableCallback(?callable $cb = null): void.{ .callable = .{ .optional = true, .nullable = true } }?phpz.Nullable(*Zval)
function resolveCallback(callable $cb): void.{ .callable = .{ .resolve = true } }*Zval
takeCallback("strlen");
optionalCallback();
optionalNullableCallback(null);
resolveCallback(static fn () => 42);

UNKNOWN is a PHP stub marker for an optional parameter whose default is handled by the extension. For optionalCallback(), the handler receives Zig null. For nullableCallback(null), it receives .null.

For resolve, supply writable storage for a zend.Callable:

var target: phpz.zend.Callable = .nil;
const args = try ctx.call.expectArgs(&.{
    .{ .callable = .{ .resolve = true } },
}, .{
    .{ .out = &target },
});

// args[0] borrows the *Zval. target now holds the resolved callable.

Accepting null

For a nullable integer, use function nullableInt(?int $n): void from the .int examples. To branch on null as a union member, use .null inside one_of:

function classify(int|string|null $value): string {}
pub fn classify(ctx: phpz.Ctx) ![]const u8 {
    const args = try ctx.call.expectArgs(&.{
        .{ .mixed = .{ .one_of = &.{ .int, .string, .null } } },
    }, {});
    return switch (args[0]) {
        .int => "integer",
        .string => "string",
        .null => "null",
    };
}
echo classify(null); // null

Optional and nullable arguments

The manual handler for function choose(?int $value = null): ?int can read both states from one argument slot:

const args = try ctx.call.expectArgs(&.{
    .{ .int = .{ .optional = true, .nullable = true } },
}, {});
if (args[0]) |provided| {
    switch (provided) {
        .null => ctx.ret(.null, {}),
        .value => |value| ctx.ret(.int, value),
    }
} else {
    ctx.ret(.int, 0);
}

This handler body handles an optional ?int. Omission returns zero, explicit null returns null and an integer returns its own value.

Handling defaults in Zig

Declare the default in the stub and handle omission in Zig. For example, the skeleton implements Counter::__construct(int $n = 0) with n: ?i64 and n orelse 0.

With ?i64, omitting the trailing argument gives the handler Zig null. Passing PHP null in weak mode emits a deprecation and passes 0 to the handler, just like an explicit zero. In strict mode, passing null raises TypeError. To handle omission, explicit null and an integer separately, declare ?int $n = null in the stub and use ?phpz.Nullable(i64) in Zig.

Named and variadic arguments

Zend assigns named arguments to positions using parameter names from the stub. If a caller skips an optional parameter and names a later one, Zend may fill the earlier slot with its stub default. optional tests presence in the current frame, so a filled slot counts as present. Extra named variadic arguments are held in a separate table outside args() and argCount().

Collecting and validating variadic arguments

This complete handler implements function countPositive(int ...$values): int and accepts positional and named arguments:

pub fn countPositive(values: phpz.Variadic) !usize {
    var count: usize = 0;
    var it = values.iterator();
    while (it.next()) |entry| {
        const value = try entry.expect(.{ .int = .{} }, {});
        if (value > 0) count += 1;
    }
    return count;
}
var_dump(countPositive(1, -2, extra: 3)); // int(2)
var_dump(countPositive());                // int(0)

Variadic must come last. For manual parsing, collect the tail with a single trailing .{ .variadic = .{} }. For example, this handler implements function countTail(string $label, mixed ...$values): int:

pub fn countTail(ctx: phpz.Ctx) !usize {
    const args = try ctx.call.expectArgs(&.{
        .{ .string = .{} },
        .{ .variadic = .{} },
    }, {});
    return args[1].len();
}

By default both positional and extra named arguments are accepted. Before processing entries, use try values.check(.positional_only), try values.check(.named_only) or try values.check(.both) to enforce a phpz.Variadic.Mode. Disallowed sources raise an error. The mode applies only to the tail. Arguments matching fixed parameter names are unrestricted and an empty tail satisfies all three modes.

len() counts the entire tail. positional borrows a slice and named borrows an optional table. iterator() visits positional arguments first and then extra named arguments in table order. Each Entry.value borrows a *Zval that preserves reference containers. name() returns an optional name. Its identifier is a phpz.ArgIdentifier with a one-based .position or a .name.

entry.expect(spec, runtime) uses the single-argument rules for weak and strict conversion, nullable types, unions, references, class constraints and runtime callable data. Conversion updates the original zval. Named-argument errors identify ($name). Only entries passed to expect receive this validation. An element specification cannot be optional or contain another .variadic.

Variadic borrows its arguments and named table for the duration of the call. Never free or structurally modify that table. Copy or retain individual values to extend their lifetime.

Without a trailing .variadic, expectArgs rejects extra named arguments. At the lower level, extraNamedArgs() gives access to the named table, args() borrows the current frame’s argument slice, and expectNoExtraNamedArgs() rejects a named tail. Check every argument yourself when using these APIs.

Passing variadic arguments by reference

The stub’s &... asks PHP to pass each caller variable by reference. Zig receives one phpz.Variadic. Copying each entry with Zval.raw.copy preserves the reference container. Inserting that copy transfers its reference to the result array, under the original name or at the next numeric index.

function collectReferenceArguments(mixed &...$args): array {}
pub fn collectReferenceArguments(ctx: phpz.Ctx, args: phpz.Variadic) !void {
    const result = phpz.Zval.Array.empty(ctx.retval.ptr());
    var it = args.iterator();
    while (it.next()) |entry| {
        var copy = phpz.Zval.raw.undef;
        phpz.Zval.raw.copy(&copy, entry.value.ptr());
        errdefer phpz.Zval.raw.release(&copy);
        if (entry.name()) |name| {
            result.set(.mixed, name, &copy);
        } else {
            try result.append(.mixed, &copy);
        }
    }
}
$a = 1;
$b = 2;
$refs = collectReferenceArguments($a, extra: $b);
$refs[0] = 10;
$b = 20;
var_dump($a, $refs["extra"]); // int(10), int(20)

Error propagation

Use try to propagate parsing and call errors to the wrapper. Parsers return PhpException or UnwindExit through phpz.exception.Error and preserve PHP’s pending state. Ordinary Zig errors become PHP Error objects. UnwindExit signals an internal exit, which may follow exit, die or deferred OOM. Propagate it and ZendBailout after native cleanup. See Cleanup rules for OutOfMemory. An error must end the normal return path.