Skip to main content

Functions

Functions are the primary way to organize reusable code in Zymba. Zymba supports named functions, anonymous functions assigned to variables, closures that capture outer scope, and higher-order functions that accept or return other functions.

The key thing to understand upfront is scope isolation: Zymba functions have their own scope and cannot access variables from the surrounding context unless those variables are passed as parameters or explicitly captured with a use clause.

Scope rules

Function scope is isolated

Variables declared outside a function are not accessible inside:

ZYMBA
$x = 42;

function $test() {
return $x; // $x is not available — returns null
}

echo $test(); // (empty)

Variables don't leak out

Variables declared inside a function don't affect the outer scope:

ZYMBA
$x = 42;

function $test() {
$x = 99; // Local $x, different from outer $x
}

$test();
echo $x; // 42 (unchanged)

Accessing outer variables

Two options for using outer variables inside a function:

  1. Pass as parameters (preferred for named functions):
ZYMBA
function $format($value, $currency) {
return $currency . @Number.format($value, 2);
}
echo $format(19.99, "$"); // "$19.99"
  1. Capture with use (closures only):
ZYMBA
$currency = "$";
$format = function($value) use ($currency) {
return $currency . @Number.format($value, 2);
};
echo $format(19.99); // "$19.99"

Function introspection

The @Function class provides reflection capabilities:

ZYMBA
$fn = function($a, $b, $c = 10) {
return $a + $b + $c;
};

echo @Function.countParameters($fn); // 3
echo @Function.isUserDefined($fn); // true
echo @Function.isVariadic($fn); // false

$names = @Function.listParameterNames($fn);
// ["a", "b", "c"]
MethodDescription
@Function.call($fn, $bind, ...$args)Call a function with explicit binding
@Function.countParameters($fn)Number of parameters
@Function.isInternal($fn)Whether the function is built-in
@Function.isUserDefined($fn)Whether the function is user-defined
@Function.isVariadic($fn)Whether the function uses ...
@Function.listParameterNames($fn)Array of parameter name strings
@Function.listParameters($fn)Array of parameter details

See also

  • Named Functions — declaration, defaults, variadic parameters, return values
  • Closures — anonymous functions, use clause, higher-order functions, patterns