AnyCompiler

Functions

function greet(string $name, string $greeting = "Hello"): string declares a function with a required parameter, a second parameter with a default value (used whenever the caller omits it), and a return type. None of the type annotations are required by the language — PHP will happily run a function with no types written anywhere — but they document intent and PHP enforces them at runtime when they are present.

A parameter prefixed with ... (the splat/variadic operator) collects any number of trailing arguments into a single array inside the function — PHP's equivalent of Python's *args or JavaScript's rest parameters.

<?php
function greet(string $name, string $greeting = "Hello"): string {
    return "$greeting, $name!";
}
echo greet("Ada"), "\n";
echo greet("Ada", "Hi"), "\n";

function total(...$nums): int {
    return array_sum($nums);
}
echo total(1, 2, 3, 4), "\n";
Output
Hello, Ada!
Hi, Ada!
10

greet("Ada") used the default "Hello" for $greeting; greet("Ada", "Hi") overrode it. total(1, 2, 3, 4) passed four separate arguments, and ...$nums gathered all four into one array ([1, 2, 3, 4]) inside the function, ready for array_sum() to add up — the caller never has to build an array themselves. Next: the null coalescing operator (?? and ??=) — PHP's concise way to supply a default when a value might not exist.

Practice exercise

Write greet(string $name, string $greeting = "Hello"): string that returns "$greeting, $name!", then echo greet("World").