Declarations and registration

Classes, properties and methods

phpz.Class("MyPHPExt\\Counter", Counter, .{}) binds a stub class to a Zig implementation and returns a wrapper type for module.classes.

Methods can use typed parameters and returns or parse arguments manually through a call context. See Argument parsing and return values.

Class registration options

The third argument to phpz.Class(name, T, options) is a compile-time options struct. Pass .{} for the defaults. All classes accept .methods and .register, including the shorthand phpz.ClassDecl(name, options). The remaining options require a Zig struct with fields as T.

OptionUsage and defaults
.methodsDefaults to .automatic, which binds methods by name. To use different Zig function names, supply a named mapping covering all concrete methods. See Method bindings.
.registerCalls the stub-generated registration function directly when it takes no arguments. If it requires a parent or interface, supply a callback that passes class entries in the generated function’s argument order. See Inheritance and interfaces.
.initDefaults to .default when every field has a default value, or .none otherwise. A zero-argument function returning T or !T can initialize the data before the PHP constructor runs.
.deinitOptional fn (*T) void callback that releases resources held by initialized instance data.
.cloneCloning a backed object is disabled by default. To enable it, supply a function taking *const T and returning T or !T. See Object lifecycle.
.gcReports PHP values held by Zig instance data to the garbage collector. The framework includes standard PHP properties automatically.
.operateImplements arithmetic or bitwise operations and writes the result to the callback’s result argument. See Operators.
.compareImplements comparison and returns .less, .equal or .greater, or an error.
.handlersOverrides selected Zend callbacks with phpz.ObjectHandlers. Each operation can be set here or through its corresponding high-level option only once. See Custom object handlers.

Zig instance data

A Zig struct with fields adds per-instance data to each PHP object. If every field has a default, phpz initializes this data automatically. Otherwise initialize it in the constructor or .init. Calling a method that requires self on an uninitialized instance raises a PHP error.

If .init returns an error, the instance data remains uninitialized. phpz marks construction as failed: new skips __construct and the object skips __destruct. The exception stays pending. Object destruction cleans up only initialized instance data.

Method bindings

In automatic mode, each pub fn corresponds to a concrete method in the stub:

<?php
namespace MyPHPExt;
class Counter {
    public function __construct(int $n = 0) {}
    public static function isPositiveStep(int $n): bool {}
    public function add(int $n): void {}
    public function value(): int {}
}
const Counter = struct {
    n: i64 = 0,

    pub fn __construct(n: ?i64) Counter {
        return .{ .n = n orelse 0 };
    }

    pub fn isPositiveStep(n: i64) bool {
        return n > 0;
    }

    pub fn add(self: *Counter, n: i64) void {
        self.n +|= n;
    }

    pub fn value(self: *const Counter) i64 {
        return self.n;
    }
};

const CounterClass = phpz.Class("MyPHPExt\\Counter", Counter, .{});
use MyPHPExt\Counter;

var_dump(Counter::isPositiveStep(3)); // bool(true)
$counter = new Counter(5);
$counter->add(3);
echo $counter->value();               // 8
PHP callZig parametersResult
new Counter(5)n: ?i64The constructor returns a Counter to initialize the object’s Zig data. PHP receives the object.
Counter::isPositiveStep(3)n: i64A static method takes only the supplied integer and returns a PHP boolean.
$counter->add(3)self: *Counter, n: i64phpz supplies the receiver from $counter. The method updates that instance and returns void.
$counter->value()self: *const CounterPHP supplies no arguments. Zig reads the receiver and returns a PHP integer.

An ordinary instance method on a class with Zig fields must take *T or *const T first. A constructor for that class takes no receiver and returns T or !T. PHP declares no constructor return type, so reflection returns null from getReturnType(). A static method also takes no receiver. When a handler needs Ctx or GuardCtx, put it before the PHP arguments and after any receiver. For classes that keep their state in PHP properties, see Standard layout method bindings.

Class and method names must match the stub exactly, including case. Automatic binding checks all public Zig functions and all concrete stub methods. Explicit @alias entries share the implementation. At compile time phpz checks parameter counts, optional and variadic parameters, and reference flags against arginfo. A backed constructor skips the PHP return-reference check. Other methods follow the function rules. Match types and defaults in the stub and implementation.

Classes with Zig instance data cannot extend a class that allocates its own objects, such as Exception, ArrayObject or another class with Zig data. Zend preserves the parent’s create_object and parent methods expect its layout. Debug builds warn and fail registration with error.UnsupportedParent. For these subclasses use void as the Zig type and keep state in PHP properties.

Use .register when a generated registration function needs a parent or interfaces. The adapter takes a tuple of *phpz.ClassEntry values in stub parameter order. Pass each wrapper’s .entry. Return *ClassEntry or an error union containing it. See Registering parent classes and interfaces.

Use .methods to map different names. The mapping must cover every concrete method. For example, rename Zig’s add to increment while keeping the PHP name add:

const CounterClass = phpz.Class("MyPHPExt\\Counter", Counter, .{
    .methods = .{
        .__construct = Counter.__construct,
        .isPositiveStep = Counter.isPositiveStep,
        .add = Counter.increment,
        .value = Counter.value,
    },
});

Keep helpers for .init, .deinit, .clone and .gc private to exclude them from automatic method binding. See Object lifetime and garbage collection for resource and clone rules.

Creating and accessing Zig instance data

After class registration, the backed CounterClass provides these operations:

APIBehavior and ownership
create()Create an object and run .init, skipping the PHP constructor. Returns an owned wrapper
new(params, named_params)Create an object and call the PHP constructor. Returns an owned wrapper
tryNew(params, named_params)Like new, but catches a Zend bailout as error.ZendBailout
fromObject(object) / fromZval(value)Check the class and handlers, then borrow the wrapper without incrementing the reference count. fromZval follows PHP references
backing()Borrow a ?*Counter, or return null for uninitialized data
object()Borrow a *zend.Object

These two global functions reuse CounterClass. Declare them in the stub first. If they are the only global functions, use phpz.functions(functions, .{ .namespace = "MyPHPExt" }). Otherwise include them in the namedFunctions mapping that covers all global functions:

namespace MyPHPExt;
function makeCounter(int $n): Counter {}
function counterValue(Counter $counter): int {}
const functions = struct {
    pub fn makeCounter(ctx: phpz.Ctx) !void {
        const args = try ctx.call.expectArgs(&.{.{ .int = .{} }}, {});
        const number = phpz.Zval.raw.init(.int, args[0]);
        const instance = try CounterClass.new(.{number}, null);
        ctx.ret(.object, instance.object());
    }

    pub fn counterValue(ctx: phpz.Ctx) !void {
        const args = try ctx.call.expectArgs(&.{
            .{ .object = .{ .instanceof = true } },
        }, .{.{ .class = CounterClass.entry }});
        const instance = try CounterClass.fromObject(args[0]);
        const data = instance.backing() orelse return error.UninitializedCounter;
        ctx.ret(.int, data.n);
    }
};

makeCounter transfers one object reference to the PHP return value. If only Zig uses the new instance, call instance.object().release() during normal cleanup. fromObject borrows its result. Do not release the input object on that account or use backing() after the object is released.

$counter = MyPHPExt\makeCounter(5);
echo MyPHPExt\counterValue($counter), PHP_EOL; // 5

fromObject accepts subclasses with compatible handlers. It returns InvalidObjectLayout for a related class with an incompatible layout and leaves initialization to the caller. Constructor exceptions return PhpException and internal exits return UnwindExit. tryNew also catches an escaping ZendBailout. End the request after UnwindExit or ZendBailout, as described in Bailouts and cleanup.

Standard layout

Use void or a Zig struct with no fields for Zend’s standard object layout. Store instance state in PHP properties declared in the stub.

Standard method bindings

With the standard layout, methods take no self. Retrieve the object with ctx.call.this() to access PHP properties:

const Counter = struct {
    pub fn __construct(ctx: phpz.Ctx, n: ?i64) !void {
        try ctx.call.this().?.setProperty(.int, "n", n orelse 0);
    }

    pub fn value(ctx: phpz.Ctx) !void {
        try ctx.call.expectNoArgs();
        const object = ctx.call.this().?;

        var scratch = phpz.Zval.raw.undef;
        defer phpz.Zval.raw.release(&scratch);

        const n = try object.property("n", false, &scratch);
        ctx.ret(.int, try n.as(.int));
    }
};

const CounterClass = phpz.Class("MyPHPExt\\Counter", Counter, .{});

Declare PHP properties in the stub. Zig struct fields alone do not expose public PHP properties.

Properties

Declare the PHP property in the stub:

<?php
namespace MyPHPExt;
class Counter {
    public int $n = 0;
    public ?string $name = null;

    public function __construct(int $n = 0) {}
    public function value(): int {}
}

In an instance method, retrieve the object with ctx.call.this() and use property or setProperty. Property access may execute user code, enforce visibility and type constraints, or raise a PHP exception.