PHP Mastery Tutorial 0/120 lessons ~6 min read Lesson 20

    Static Variables, Variadic Functions & Argument Unpacking

    Learn PHP static variables, variadic functions (...$args), and argument unpacking — flexible functions for dynamic data in Laravel and modern PHP.

    Course progress0%
    Focus
    28 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Static Variables, Variadic Functions & Argument Unpacking

    Introduction

    In the previous lesson, you learned about:

    • Default Parameters
    • Named Arguments
    • Local Scope
    • Global Scope
    • $GLOBALS

    These features help you write flexible and maintainable functions.

    However, modern PHP applications often require functions that can:

    • Remember previous values.
    • Accept any number of arguments.
    • Pass array elements as individual parameters.
    • Handle dynamic data from APIs, forms, or databases.

    PHP provides three powerful features for these scenarios:

    • Static Variables
    • Variadic Functions (...$args)
    • Argument Unpacking (...)

    These features are widely used in modern PHP frameworks such as Laravel, Symfony, and CodeIgniter.

    Static Variables

    Normally, every time a function finishes execution, all its local variables are destroyed.

    Example:

    php
    <?php
    function counter()
    {
    $count = 0;
    $count++;
    echo $count . "<br>";
    }
    counter();
    counter();
    counter();

    Output:

    1
    1
    1

    Why?

    Because $count is recreated every time the function is called.

    What is a Static Variable?

    A static variable keeps its value between function calls.

    Instead of being destroyed when the function finishes, PHP stores it in memory for future calls.

    Syntax:

    php
    static $variable;

    Example

    php
    <?php
    function counter()
    {
    static $count = 0;
    $count++;
    echo $count . "<br>";
    }
    counter();
    counter();
    counter();

    Output:

    1
    2
    3

    Unlike a normal local variable, $count remembers its previous value.

    How Static Variables Work

    First call:

    $count = 0
    $count++
    Result = 1

    Second call:

    $count = 1
    $count++
    Result = 2

    Third call:

    $count = 2
    $count++
    Result = 3

    The variable is initialized only once.

    Real-World Example: Visitor Counter

    php
    <?php
    function pageVisits()
    {
    static $visits = 0;
    $visits++;
    echo "Visits: " . $visits . "<br>";
    }
    pageVisits();
    pageVisits();
    pageVisits();

    Output:

    Visits: 1
    Visits: 2
    Visits: 3

    In real applications, visitor counts are usually stored in a database or cache, but this example demonstrates how static variables retain state within the current request.

    Real-World Example: Logging Function Calls

    php
    <?php
    function logRequest()
    {
    static $requestNumber = 0;
    $requestNumber++;
    echo "Processing Request #" . $requestNumber . "<br>";
    }
    logRequest();
    logRequest();
    logRequest();

    Output:

    Processing Request #1
    Processing Request #2
    Processing Request #3

    When Should You Use Static Variables?

    Static variables are useful when a function needs to remember information during the current script execution.

    Examples include:

    • Counting function calls.
    • Generating temporary sequence numbers.
    • Caching expensive calculations within the same request.
    • Preventing repeated initialization.

    Remember that static variables are not shared across different HTTP requests. They exist only while the current PHP script is running.

    Static Variable vs Local Variable

    FeatureLocal VariableStatic Variable
    Created Every Function CallYesNo
    Keeps Previous ValueNoYes
    ScopeLocalLocal
    LifetimeUntil function endsUntil script execution ends

    Variadic Functions

    Sometimes you don't know how many arguments a function will receive.

    For example:

    • Shopping cart items.
    • Student marks.
    • Product prices.
    • Order totals.
    • User roles.

    PHP solves this problem using Variadic Functions.

    A variadic function accepts zero or more arguments.

    Syntax

    php
    function functionName(...$values)
    {
    }

    The ... operator collects all remaining arguments into an array.

    Example

    php
    <?php
    function displayNumbers(...$numbers)
    {
    print_r($numbers);
    }
    displayNumbers(10, 20, 30, 40);

    Output:

    Array
    (
        [0] => 10
        [1] => 20
        [2] => 30
        [3] => 40
    )

    PHP automatically stores the arguments in an array.

    Loop Through Variadic Arguments

    php
    <?php
    function printNames(...$names)
    {
    foreach ($names as $name) {
    echo $name . "<br>";
    }
    }
    printNames("Rahul", "John", "Priya");

    Output:

    Rahul
    John
    Priya

    Real-World Example: Shopping Cart Total

    php
    <?php
    function calculateTotal(...$prices)
    {
    $total = 0;
    foreach ($prices as $price) {
    $total += $price;
    }
    return $total;
    }
    echo calculateTotal(100, 250, 400, 150);

    Output:

    900

    No matter how many prices are passed, the function works correctly.

    Real-World Example: Student Average

    php
    <?php
    function averageMarks(...$marks)
    {
    return array_sum($marks) / count($marks);
    }
    echo averageMarks(80, 90, 75, 95);

    Output:

    85

    Notice how the function accepts any number of marks.

    Combining Required and Variadic Parameters

    Variadic parameters must appear last.

    Correct:

    php
    function sendNotification($title, ...$users)
    {
    }

    Example:

    php
    <?php
    function sendNotification($title, ...$users)
    {
    foreach ($users as $user) {
    echo $title . " sent to " . $user . "<br>";
    }
    }
    sendNotification(
    "Meeting Reminder",
    "Rahul",
    "John",
    "Priya"
    );

    Output:

    Meeting Reminder sent to Rahul
    Meeting Reminder sent to John
    Meeting Reminder sent to Priya

    Argument Unpacking

    Variadic functions collect arguments.

    Argument unpacking does the opposite.

    It expands an array into individual arguments.

    Example

    Suppose you have:

    php
    $numbers = [10, 20];

    And a function:

    php
    function add($a, $b)
    {
    return $a + $b;
    }

    Instead of writing:

    php
    echo add($numbers[0], $numbers[1]);

    Use argument unpacking:

    php
    echo add(...$numbers);

    Output:

    30

    PHP expands the array automatically.

    Real-World Example: Order Calculation

    php
    <?php
    function calculateOrder($price, $tax)
    {
    return $price + $tax;
    }
    $order = [1000, 180];
    echo calculateOrder(...$order);

    Output:

    1180

    This technique is useful when working with arrays returned from APIs or helper functions.

    Real-World Example: User Registration

    php
    <?php
    function registerUser($name, $email, $role)
    {
    echo "$name | $email | $role";
    }
    $user = [
    "Rahul",
    "rahul@example.com",
    "Admin"
    ];
    registerUser(...$user);

    Output:

    Rahul | rahul@example.com | Admin

    Variadic Functions with Type Declarations

    You can also specify the expected type.

    php
    <?php
    function total(int ...$numbers)
    {
    return array_sum($numbers);
    }
    echo total(10, 20, 30);

    Output:

    60

    Every argument must be an integer.

    Type declarations help prevent accidental misuse of functions.

    Performance Considerations

    Static variables can reduce repeated work within a single request by storing values that don't need to be recalculated.

    Variadic functions and argument unpacking add a small amount of flexibility with minimal overhead. In most applications, the impact is negligible compared to database queries, API calls, or file operations.

    Choose these features because they make your code clearer and more maintainable, not because of perceived performance gains.

    Best Practices

    Keep Functions Focused

    A variadic function should still have a single responsibility.

    Good example:

    php
    calculateTotal(...$prices)

    Not:

    php
    processEverything(...$data)

    Use Static Variables Sparingly

    Static variables are useful, but they can make functions harder to reason about if overused. Use them only when retaining state within the current request is genuinely beneficial.

    Validate Variadic Input

    If your function expects numbers, validate or type-hint the arguments. This helps catch errors early.

    Prefer Descriptive Names

    Bad:

    php
    function test(...$x)

    Better:

    php
    function calculateInvoiceTotal(...$amounts)

    Use Argument Unpacking with Matching Data

    Ensure the array contains values in the order expected by the function. If the order is incorrect, the function may receive invalid arguments.

    Common Mistakes

    Forgetting That Static Variables Persist

    php
    static $count = 0;

    Remember that the value is retained during the current script execution. If you expect a fresh value on every call, use a normal local variable instead.

    Placing Variadic Parameters Before Required Parameters

    Incorrect:

    php
    function demo(...$values, $title)
    {
    }

    The variadic parameter must always be last.

    Assuming Variadic Arguments Are Strings

    Variadic arguments are stored in an array and may contain any type unless you specify type declarations.

    Unpacking Arrays with Missing Values

    php
    $data = [100];
    echo add(...$data);

    If the target function expects two parameters, PHP will report an error because one argument is missing.

    Ignoring Readability

    Although variadic functions are flexible, avoid using them when a fixed number of parameters makes the function's purpose clearer.

    Hands-on Exercise

    Create a PHP program that:

    1. Uses a static variable to count function calls.
    2. Creates a variadic function that calculates the total salary of multiple employees.
    3. Creates a variadic function that prints any number of city names.
    4. Uses argument unpacking to pass an array of product prices into a calculation function.
    5. Combines a required parameter with a variadic parameter to send a notification to multiple users.
    6. Creates a typed variadic function that accepts only integers and returns their sum.

    Challenge yourself to solve these exercises before referring to any solutions.

    Summary

    Static variables, variadic functions, and argument unpacking are powerful tools for writing flexible and reusable PHP code.

    Static variables allow a function to remember information during the current request, variadic functions make it easy to accept an unknown number of arguments, and argument unpacking simplifies passing array values into functions.

    These features are commonly used in modern PHP applications and frameworks because they help developers write cleaner, more expressive code.

    Key Takeaways

    • Static variables retain their values between function calls within the same script execution.
    • Variadic functions accept any number of arguments using the ... operator.
    • Variadic arguments are collected into an array automatically.
    • Argument unpacking expands an array into individual function arguments.
    • Variadic parameters must always appear last.
    • Type declarations can be combined with variadic functions for safer code.
    • Use these features to improve readability and reduce repetitive code, not as premature performance optimizations.

    Next Lesson (Part 2B-2)

    You'll learn advanced modern PHP function features used in production applications:

    • Scalar Type Declarations
    • declare(strict_types=1)
    • Return Type Declarations
    • Union Types (PHP 8+)
    • Nullable Types
    • mixed Type
    • never Return Type (PHP 8.1+)
    • Real-World Examples
    • Best Practices
    • Common Mistakes
    • Hands-on Exercises
    • Professional Interview Questions with Expert Answers
    Ready to mark this lesson complete?Track your journey across the entire course.