Functions
⏱ 15 min read read
Defining Functions:
function greet(string $name): void {
echo "Hello, $name!";
}
function add(int $a, int $b): int {
return $a + $b;
}
PHP 7+ supports type hints for parameters and return types.
Type hints make code safer and self-documenting.
Use : void for functions that return nothing.
Use ?string for nullable types (string or null).
Default Arguments:
function createProfile(string $name, string $city = "Unknown",
string $role = "User"): string {
return "$name from $city [$role]";
}
echo createProfile("Alice", "Lagos", "Admin");
echo createProfile("Bob"); // uses defaults
Variadic Functions (...$args):
function addAll(int ...$numbers): int {
return array_sum($numbers);
}
echo addAll(1, 2, 3); // 6
echo addAll(10, 20, 30, 40); // 100
Anonymous Functions & Arrow Functions:
// Anonymous function
$square = function(int $x): int { return $x ** 2; };
echo $square(5); // 25
// Arrow function (PHP 7.4+) --- cleaner syntax
$square = fn(int $x): int => $x ** 2;
echo $square(5); // 25
// Arrow functions capture outer variables automatically
$multiplier = 3;
$triple = fn($x) => $x * $multiplier; // $multiplier captured
echo $triple(5); // 15
Pass by Reference:
function addTen(int &$n): void {
$n += 10;
}
$value = 5;
addTen($value);
echo $value; // 15 --- modified in place
function greet(string $name): void {
echo "Hello, $name!";
}
function add(int $a, int $b): int {
return $a + $b;
}
PHP 7+ supports type hints for parameters and return types.
Type hints make code safer and self-documenting.
Use : void for functions that return nothing.
Use ?string for nullable types (string or null).
Default Arguments:
function createProfile(string $name, string $city = "Unknown",
string $role = "User"): string {
return "$name from $city [$role]";
}
echo createProfile("Alice", "Lagos", "Admin");
echo createProfile("Bob"); // uses defaults
Variadic Functions (...$args):
function addAll(int ...$numbers): int {
return array_sum($numbers);
}
echo addAll(1, 2, 3); // 6
echo addAll(10, 20, 30, 40); // 100
Anonymous Functions & Arrow Functions:
// Anonymous function
$square = function(int $x): int { return $x ** 2; };
echo $square(5); // 25
// Arrow function (PHP 7.4+) --- cleaner syntax
$square = fn(int $x): int => $x ** 2;
echo $square(5); // 25
// Arrow functions capture outer variables automatically
$multiplier = 3;
$triple = fn($x) => $x * $multiplier; // $multiplier captured
echo $triple(5); // 15
Pass by Reference:
function addTen(int &$n): void {
$n += 10;
}
$value = 5;
addTen($value);
echo $value; // 15 --- modified in place
Log in to track your progress and earn badges as you complete lessons.
Log In to Track Progress