Variables ᴾᴴᴾ - chung-leong/zigar GitHub Wiki
JavaScript | PHP
Variables declared in a Zig module are accessible in PHP provided they're public.
const std = @import("std");
pub const numeric_constant: i32 = 1234;
pub var numeric_variable: i32 = 43;
pub fn printNumericVariable() {
std.debug.print("From Zig: {d}\n", .{numeric_variable});
}
<?php
$m = zigar_use(__DIR__ . '/variable-example-1.zig');
echo "$m->numeric_constant\n";
$m->numeric_variable = 777;
$m->printNumericVariable();
1234
From Zig: 777
Limitations
A pointer that exist in the Zig memory space can only point to objects living in the same space. It cannot point to an object in PHP memory, where objects be garbage-collected at any time. An error would occur if you attempt to assign such an object to a pointer variable in a module:
const std = @import("std");
pub const User = struct {
name: []const u8,
role: []const u8,
};
pub const default_user: User = .{
.name = "nobody",
.role = "none",
};
pub var current_user: *const User = &default_user;
pub fn printCurrentUser() void {
std.debug.print("{s} ({s})\n", .{ current_user.name, current_user.role });
}
<?php
$m = zigar_use(__DIR__ . '/variable-example-2.zig');
$m->printCurrentUser();
try {
$m->current_user = new $m->User(name: 'batman72', role: 'vigilante');
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
nobody (none)
pointers in Zig memory cannot point to garbage-collected object (zig)
In order to create an object that exists in Zig's memory space, you'd need to get an
Allocator from Zig and supply it to the constructor using its
optional options argument:
const std = @import("std");
pub const User = struct {
name: []const u8,
role: []const u8,
};
pub const default_user: User = .{
.name = "nobody",
.role = "none",
};
pub var current_user: *const User = &default_user;
var gpa = std.heap.DebugAllocator(.{}).init;
pub const allocator = gpa.allocator();
pub fn printCurrentUser() void {
std.debug.print("{s} ({s})\n", .{ current_user.name, current_user.role });
}
<?php
$m = zigar_use(__DIR__ . '/variable-example-3.zig');
$m->printCurrentUser();
$m->current_user = new $m->User(name: 'batman72', role: 'vigilante', allocator: $m->allocator);
$m->printCurrentUser();
nobody (none)
batman72 (vigilante)