Skip to main content

Named Functions

Declaring named functions

Declare a function with the function keyword. Function names use the $ prefix:

ZYMBA
function $add($a, $b) {
return $a + $b;
}

echo $add(3, 4); // 7

Default parameter values

Parameters can have default values:

ZYMBA
function $greet($name = "World") {
return "Hello, " . $name;
}

echo $greet(); // "Hello, World"
echo $greet("Alice"); // "Hello, Alice"

Defaults work from right to left — optional parameters must come after required ones:

ZYMBA
function $createUser($name, $role = "user", $active = true) {
return [name: $name, role: $role, active: $active];
}

$user = $createUser("Alice"); // role="user", active=true
$admin = $createUser("Bob", "admin"); // active=true

Variadic functions

Accept any number of arguments with the ... spread operator:

ZYMBA
function $sum(...$nums) {
$total = 0;
for ($nums as $n) {
$total += $n;
}
return $total;
}

echo $sum(1, 2, 3, 4, 5); // 15

Combine regular parameters with variadic:

ZYMBA
function $log($level, ...$parts) {
$message = @Array.joinValues($parts, " ");
echo "[$level] $message\n";
}

$log("ERROR", "Connection", "failed", "to", "server");
// Output: [ERROR] Connection failed to server

Return values

Functions return values with the return statement. Without an explicit return, the function returns null:

ZYMBA
function $divide($a, $b) {
if ($b == 0) {
return null;
}
return $a / $b;
}

Functions can return any type — scalars, arrays, objects, or even other functions:

ZYMBA
function $parseConfig($json) {
try {
return @Var.fromJSON($json);
} catch ($e) {
return [error: $e.getMessage()];
}
}

Common pitfall: forgetting to pass outer variables

Named functions have isolated scope and cannot access variables from the surrounding context:

ZYMBA
// Wrong — $db is undefined inside the function
$db = @ZeyOS.selectDatabase();
function $getUser($id) {
return $db.fetchOne(@SQL.prepare("SELECT * FROM contacts WHERE ID = ?", $id), true);
}

// Correct — pass as parameter
function $getUser($db, $id) {
return $db.fetchOne(@SQL.prepare("SELECT * FROM contacts WHERE ID = ?", $id), true);
}