PHP Functions

PHP Functions

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.

1 - Defining and Calling

function greet(string $name): string {
    return "Hello, $name!";
}

echo greet("Alice"); // Hello, Alice!

2 - Default Parameter Values

function greet(string $name = "World"): string {
    return "Hello, $name!";
}

echo greet();        // Hello, World!
echo greet("Bob");   // Hello, Bob!

3 - Named Arguments (PHP 8)

function createUser(string $name, int $age, string $role = "user"): array {
    return compact("name", "age", "role");
}

$user = createUser(age: 25, name: "Alice", role: "admin");

4 - Variable Scope

$counter = 0;

function increment(): void {
    global $counter;
    $counter++;
}

increment();
echo $counter; // 1

5 - Anonymous Functions and Arrow Functions

// 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

Note: Arrow functions (fn) automatically capture variables from the outer scope by value, making them perfect for short callbacks passed to array functions like array_map() and array_filter().

-Tip-