Skip to main content

Classes and Constructors

Defining a class

A class is an object definition that serves as a template. The construct() method is called when creating instances with new:

ZYMBA
$Product = new object() {
name;
price;
stock;

construct($name, $price, $stock = 0) {
$this.name = $name;
$this.price = $price;
$this.stock = $stock;
}

getTotal() {
return $this.price * $this.stock;
}

isAvailable() {
return $this.stock > 0;
}
};

Creating instances

Use new with the class variable and constructor arguments:

ZYMBA
$widget = new $Product("Widget", 9.99, 100);
$gadget = new $Product("Gadget", 29.99);

echo $widget.name; // "Widget"
echo $widget.getTotal(); // 999
echo $gadget.isAvailable(); // false (stock defaults to 0)

Each instance is independent — modifying one does not affect others:

ZYMBA
$widget.stock = 50;
echo $widget.getTotal(); // 499.5
echo $gadget.stock; // 0 (unchanged)

Property declarations

Properties can be declared with or without default values:

ZYMBA
$Config = new object() {
host = "localhost"; // Default value
port = 3306; // Default value
database; // No default (null)
username; // No default (null)

construct($db, $user) {
$this.database = $db;
$this.username = $user;
}
};

Method chaining

Return $this from methods to enable fluent interfaces:

ZYMBA
$QueryBuilder = new object() {
table;
conditions = [];
limit;

from($t) {
$this.table = $t;
return $this;
}

where($cond) {
$this.conditions[] = $cond;
return $this;
}

take($n) {
$this.limit = $n;
return $this;
}

build() {
$sql = "SELECT * FROM " . $this.table;
if (count $this.conditions > 0) {
$sql .= " WHERE " . @Array.joinValues($this.conditions, " AND ");
}
if (exists $this.limit) {
$sql .= " LIMIT " . $this.limit;
}
return $sql;
}
};

$sql = (new $QueryBuilder())
.from("contacts")
.where("active = 1")
.where("type = 'customer'")
.take(10)
.build();
// "SELECT * FROM contacts WHERE active = 1 AND type = 'customer' LIMIT 10"

This pattern appears extensively in ZeyOS platform code:

ZYMBA
new @ZeyOS.ObjectTransaction()
.setFields([name: "New Item", price: 19.99])
.setItems([$items])
.save();

Dynamic method calls

Call methods by name using bracket notation:

ZYMBA
$calc = new object() {
add($a, $b) { return $a + $b; }
mul($a, $b) { return $a * $b; }
};

$operation = "add";
$result = $calc[$operation](3, 4); // 7