zigar_import(path, callback = null, params = null) ᴾᴴᴾ - chung-leong/zigar GitHub Wiki

JavaScript | PHP


Import functions and constants from a Zig module into PHP's global namespace, using names from a callback function.

If path points to a source file, the extension would first recompile the module (unless recompile is turned off in php.ini). The module path would be derived by combining the directory containg the source file with module_rel_path.

Global variables in the module are not imported. They can only be accessed through the module object.

Usage:

const std = @import("std");
pub const pi = std.math.pi;

pub const Point = struct {
    x: f64,
    y: f64,
};

pub var number: i32 = 123;

pub fn hello() void {
    return std.debug.print("Hello world\n", .{});
}
<?php

$m = zigar_import(__DIR__ . '/import-example-1.zig', function($name, $type) {
    switch ($type) {
        case 'class': return "PFJ$name";
        case 'function': return "pfj_$name";
        case 'constant': return "PFJ_" . strtoupper($name);
    }
});
$point = new PFJPoint(x: 123, y: 456);
print_r($point);
pfj_hello();
echo PFJ_PI, "\n";
PFJPoint Object
(
    [x] => 123
    [y] => 456
)
Hello world
3.1415926535898

If no callback is given, then the symbols are imported as they're named in the Zig source file:

<?php

$m = zigar_import(__DIR__ . '/import-example-1.zig', [ 'optimize' => 'ReleaseSmall' ]);

hello();
Hello world

If the callback returns null or false, the symbol is omitted:

<?php

$m = zigar_import(__DIR__ . '/import-example-1.zig', function ($name, $type) {
    if ($type === 'class') return null;
    return $name;
});

$obj = new Point(x: 1, y: 0);
PHP Fatal error:  Uncaught Error: Class "Point" not found in /home/rwiggum/examples/import-example-1g.php:8

The function does not check whether strings returned by the callback are proper identifiers in PHP:

<?php

$m = zigar_import(__DIR__ . '/import-example-1.zig', function ($name, $type) {
    return ($type === 'function') ? '¯\_(ツ)_/¯' : $name;
});

'¯\_(ツ)_/¯'();
Hello world

Use __zigar‐>unimport() to remove the imported symbols. Doing so allows the module to be garbage-collected.

Arguments:

  • path - Path to the .zig file or .zigar directory
  • callback - Callback function providing alternative names for symbols in the module
  • params - Array containing configuration parameters overriding those set through php.ini

Return value:

object


Top-level functions | __zigar->import() | __zigar‐unimport()