Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A function in PHP is a named, reusable block of statements that encapsulates specific logic. It operates within its own local execution context, executes only when explicitly invoked, and can accept input via parameters and return a value to the calling scope. In PHP, user-defined functions are globally scoped by default, meaning a function defined inside an if statement or another function becomes globally accessible once the declaration block is executed.

Core Syntax and Anatomy

A function is declared using the function keyword, followed by an identifier, a comma-separated list of parameters enclosed in parentheses, and a block of code enclosed in curly braces.
function identifier(string $param1, string $param2 = 'default'): string {
    // Execution context
    return $param1 . $param2;
}

Parameters and Arguments

PHP functions support several mechanisms for handling input arguments:
  • Pass by Value (Default): The function receives a copy of the variable’s value. Mutations inside the function do not affect the original variable.
  • Pass by Reference: By prepending an ampersand (&) to the parameter name, the function receives a reference to the original variable. Mutations directly affect the variable in the calling scope.
  • Default Arguments: Parameters can be assigned constant default values, making them optional during invocation. Optional parameters must be defined after any mandatory parameters.
  • Variadic Parameters: Using the splat operator (...), a function can accept an indefinite number of arguments, which are collected into an array.
  • Named Arguments (PHP 8.0+): Arguments can be passed based on the parameter name rather than their positional order, allowing developers to skip optional parameters. Positional arguments cannot be placed after named arguments.
// Pass by reference and variadic parameters
function processData(string &$target, int ...$numbers): void {
    foreach ($numbers as $number) {
        $target .= $number;
    }
}

$myString = "Sequence: ";

// Positional arguments with argument unpacking for the variadic parameter
processData($myString, ...[1, 2, 3]);

// Named arguments invocation
function configure(string $host, int $port, bool $secure = true): void {
    // Execution context
}

// Order is independent of the declaration; optional parameters can be skipped
configure(port: 443, host: 'example.com');

Type Declarations and Strict Types

PHP allows explicit type hinting for both parameters and return values. Supported types include scalar types (int, float, string, bool), compound types (array, callable, iterable), objects, and special return types like void (returns nothing) and never (function terminates execution via exit, die, or throwing an exception). PHP 8.0+ supports Union Types (e.g., int|float) and PHP 8.1+ supports Intersection Types (e.g., ClassA&InterfaceB). By default, PHP attempts to coerce mismatched types (e.g., converting a string "5" to an integer 5). This behavior is overridden by declaring strict types at the top of the file, which forces a TypeError if the exact type is not provided.
declare(strict_types=1);

function calculate(int|float $a, int|float $b): int|float {
    return $a + $b;
}

Variable Scope

Variables declared outside a function are not accessible inside it, and vice versa. PHP functions handle scope through specific keywords:
  • Local Scope: Variables instantiated inside the function are destroyed when the function terminates.
  • Global Scope: To access a globally scoped variable inside a function, it must be explicitly imported using the global keyword or accessed via the $GLOBALS superglobal array.
  • Static Variables: The static keyword allows a local variable to retain its value across multiple invocations of the function without exposing it to the global scope.
function incrementCounter(): int {
    static $counter = 0;
    $counter++;
    return $counter;
}

Anonymous Functions and Arrow Functions

PHP supports first-class functions, allowing functions to be assigned to variables, passed as arguments, or returned from other functions. Anonymous Functions (Closures): Functions without a specified name. They must explicitly inherit variables from the parent scope using the use construct.
$multiplier = 2;
$multiply = function(int $value) use ($multiplier): int {
    return $value * $multiplier;
};
Arrow Functions (PHP 7.4+): A more concise syntax for anonymous functions (fn() => expression). Arrow functions automatically capture variables from the parent scope by value (implicit by-value scope binding). They consist of a single expression, which is implicitly returned.
$multiplier = 2;
$multiply = fn(int $value): int => $value * $multiplier;
Master PHP with Deep Grasping Methodology!Learn More