Repository navigation
Defining constants
Chung Leong edited this page Nov 17, 2026
·
4 revisions
Use the @"export ..." prefix in Extension.zig to declare global constants:
pub const @"export CONST_STRING" = "Hello world";
pub const @"export CONST_INT" = 1234;
pub const @"export CONST_FLOAT" = 3.14159265359;
pub const @"export CONST_BOOL" = 1234;<?php
var_dump(CONST_STRING);
var_dump(CONST_INT);
var_dump(CONST_FLOAT);
var_dump(CONST_BOOL);string(11) "Hello world"
int(1234)
float(3.14159265359)
int(1234)
The name of the constant may include a namespace:
pub const @"export foo\\bar\\CONST_STRING" = "Hello world";<?php
use const foo\bar\CONST_STRING;
var_dump(CONST_STRING);string(11) "Hello world"
Class constants are declared in a manner similiar to that for global constants:
const php = @import("php/root.zig");
pub const @"export Hello" = php.Class.Custom(struct {
pub const @"export string" = "Hello world";
pub const @"export int" = 12345;
});<?php
var_dump(Hello::string);
var_dump(Hello::int);string(11) "Hello world"
int(12345)
Bit fields of a packed struct are available as class constants when it's used to create a custom class. This provides an alternate way of specifying active fields:
const php = @import("php/root.zig");
pub const @"export Flags" = php.Class.Custom(packed struct {
is_cheap: bool = false,
is_fast: bool = false,
is_good: bool = false,
pub const @"use auto getters" = true;
pub const @"use auto setters" = true;
});<?php
$flags_obj = new Flags();
$flags_obj->is_fast = $flags_obj->is_good = true;
$flags_int = Flags::is_fast | Flags::is_good;
var_dump($flags_obj);
var_dump((int) $flags_obj);
var_dump($flags_int);object(Flags)#1 (3) {
["is_cheap"]=>
bool(false)
["is_fast"]=>
bool(true)
["is_good"]=>
bool(true)
}
int(6)
int(6)
Arrays and objects can be used as constants:
const php = @import("php/root.zig");
pub const @"export CONST_ARRAY" = .{ 1, 2, 3, 4 };
pub const @"export CONST_OBJECT" = .{ .hello = 123, .world = 456 };
pub const @"export Hello" = php.Class.Custom(struct {
pub const @"export array" = .{ 1, 2, 3, 4 };
pub const @"export object" = .{ .hello = 123, .world = 456 };
});<?php
var_dump(CONST_ARRAY);
var_dump(CONST_OBJECT);
var_dump(Hello::array);
var_dump(Hello::object);array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
object(stdClass)#1 (2) {
["hello"]=>
int(123)
["world"]=>
int(456)
}
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
object(stdClass)#2 (2) {
["hello"]=>
int(123)
["world"]=>
int(456)
}
Note: PHP 8.4 and below are missing a feature needed for creation of constant objects. In these
earlier versions, a struct would get turned into an associative array instead of a stdclass.
This behavior is only applicable to class constants.