> ## 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.

# PHP Function

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.

```php theme={"dark"}
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.

```php theme={"dark"}
// 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.

```php theme={"dark"}
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.

```php theme={"dark"}
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.

```php theme={"dark"}
$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.

```php theme={"dark"}
$multiplier = 2;
$multiply = fn(int $value): int => $value * $multiplier;
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor PHP Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
