A function is a reusable block of code that performs a specific task. PHP has thousands of built-in functions and lets you define your own.
function greet(string $name): string {
return "Hello, $name!";
}
echo greet("Alice"); // Hello, Alice!
function greet(string $name = "World"): string {
return "Hello, $name!";
}
echo greet(); // Hello, World!
echo greet("Bob"); // Hello, Bob!
function createUser(string $name, int $age, string $role = "user"): array {
return compact("name", "age", "role");
}
$user = createUser(age: 25, name: "Alice", role: "admin");
$counter = 0;
function increment(): void {
global $counter;
$counter++;
}
increment();
echo $counter; // 1
// Closure
$multiply = function(int $x, int $y): int {
return $x * $y;
};
// Arrow function (PHP 7.4+) — auto-captures outer variables
$factor = 3;
$triple = fn(int $x): int => $x * $factor;
echo $triple(7); // 21