Functions
Functions
Write reusable PHP functions with parameters, return values, and modern PHP 8 features.
Defining Functions
Functions are defined with the function keyword. PHP 7+ supports return type declarations.
PHP 8 Features
- Named arguments: Pass arguments by name, in any order
- Union types: Accept multiple types for a parameter
- Match expression: Cleaner alternative to switch
Arrow Functions
PHP 7.4+ supports concise arrow function syntax for short callbacks.
Variable Functions and Closures
PHP supports first-class functions — you can assign functions to variables and pass them as arguments.
Example
php
<?php
// Basic function
function greet(string $name): string {
return "Hello, $name!";
}
echo greet("Alice");
// Default parameters
function connect(string $host = "localhost", int $port = 3306): string {
return "$host:$port";
}
echo connect(); // localhost:3306
echo connect("db.example.com"); // db.example.com:3306
// Named arguments (PHP 8.0+)
function createUser(string $name, int $age, string $role = "user"): array {
return compact("name", "age", "role");
}
$user = createUser(age: 25, name: "Bob");
// Union types (PHP 8.0+)
function processId(int|string $id): string {
return "ID: $id";
}
// Arrow functions (PHP 7.4+)
$multiplier = 3;
$triple = fn($n) => $n * $multiplier;
echo $triple(5); // 15
// Closures
$greetFn = function(string $name) use ($greeting): string {
return "$greeting, $name!";
};
// Array of functions
$operations = [
"add" => fn($a, $b) => $a + $b,
"sub" => fn($a, $b) => $a - $b,
"mul" => fn($a, $b) => $a * $b,
];
echo $operations["add"](5, 3); // 8
// Recursive function
function factorial(int $n): int {
if ($n <= 1) return 1;
return $n * factorial($n - 1);
}
echo factorial(5); // 120Try It Yourself