PHP: Define function with default arguments

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

In PHP, functions can be designed to use default arguments to provide greater flexibility and prevent common errors. This tutorial explains how to define such functions with illustrative examples.

Understanding Default Arguments

Default arguments in PHP mean that when a function is called without an argument that has a default value, the function uses that default value. It’s beneficial in multiple situations, particularly when you have parameters that commonly hold a specific value.

Syntax:

function functionName($param1, $param2 = 'default') {
    // function body
}

This defines a function where $param2 is optional and will default to ‘default’ if not provided.

Basic Example

The most straightforward example of a default argument is a greeting function:

function greet($name, $greeting = 'Hello') {
    return "{$greeting}, {$name}!";
}

// Calling the function with both arguments
echo greet('Alice', 'Hi'); // Outputs: Hi, Alice!

// Calling the function with only one argument
echo greet('Alice'); // Outputs: Hello, Alice!

Advanced Usage of Default Arguments

Once the basic concept is clear, you can use default arguments in more sophisticated ways. For instance, default values can be expressions that are evaluated each time the function is called.

function addTimeStamp($note, $time = null) {
    $time = $time ?? date('Y-m-d H:i:s');
    return "{$note} - {$time}";
}

// Using the current timestamp as default
echo addTimeStamp('Reminder'); // e.g., Reminder - 2023-04-01 12:00:00

Handling Type Declarations with Default Arguments

Starting from PHP 7.x, you can add type declarations to function parameters. Combining type declarations with default arguments can lead to cleaner code.

function processOrder(int $orderId, bool $notifyCustomer = true) {
    // Process order logic
    if ($notifyCustomer) {
        // Send notification
    }
    return true;
}

Default Arguments and Reference Parameters

You can also use references with default arguments. However, the default value cannot be an expression that assigns by reference.

function setCounter(&$counter, $value = 10) {
    $counter = $value;
}

$myCounter = 5;
setCounter($myCounter, 15); // $myCounter is now 15
setCounter($myCounter); // $myCounter is now 10

Considerations and Best Practices

When defining functions with default arguments, it’s important to note that any arguments that follow a default argument must also have a default value. Also, using default arguments can help reduce function overloading.

Advanced Function Definitions

For more complex scenarios, a function might combine default arguments with a variable number of arguments. This can be managed using the ... token.

function complexFunction($compulsory, $optional = 'default', ...$extras) {
    echo "Compulsory: $compulsory\nOptional: $optional\n";
    foreach ($extras as $extra) {
        echo "Extra argument: $extra\n";
    }
}

complexFunction('Test', 'Optional', 'Extra1', 'Extra2');
// Outputs:
// Compulsory: Test
// Optional: Optional
// Extra argument: Extra1
// Extra argument: Extra2

Using Default Arguments to Simulate Named Parameters

One practice in using default arguments is to simulate named parameters by passing an associative array.

function buildQuery($table, $fields = ['*'], $conditions = null) {
    // Build SQL query logic
}

// This provides clarity at the point of call.
buildQuery('users', ['id', 'name'], 'id = 10');

Conclusion

We covered the advantages and practices of using default arguments in PHP functions and explored basic to advanced examples. Utilizing default arguments effectively can make your functions both robust and flexible.