__zigar‐>import(callback = null) ᴾᴴᴾ - chung-leong/zigar GitHub Wiki
JavaScript | PHP
Import functions and constants into PHP's global namespace, using results from a callback function as their names.
const std = @import("std");
pub fn hello() void {
return std.debug.print("Hello world\n", .{});
}
<?php
$m = zigar_use(__DIR__ . '/import-example-1.zig');
$m->__zigar->import(function($name, $type) {
echo "$name = $type\n";
return "donut_$name";
});
echo donut_pi, "\n";
donut_hello();
pi = constant
Point = class
hello = function
3.1415926535898
Hello world
If no callback is given, then the symbols are imported as they're named in the Zig source file:
<?php
$m = zigar_use(__DIR__ . '/import-example-1.zig');
$m->__zigar->import();
hello();
Hello world
If the callback returns null or false, the symbol is omitted:
<?php
$m = zigar_use(__DIR__ . '/import-example-1.zig');
$m->__zigar->import(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-1c.php:9
The function does not check whether strings returned by the callback are proper identifiers in PHP:
<?php
$m = zigar_use(__DIR__ . '/import-example-1.zig');
$m->__zigar->import(function ($name, $type) {
return ($type === 'function') ? '¯\_(ツ)_/¯' : $name;
});
'¯\_(ツ)_/¯'();
Hello world
You can use the top-level function zigar_import() to accomplish the same task.
Use __zigar‐>unimport() to remove the imported symbols. Doing allows the module to be garbage-collected.