0% complete

Functions · Lesson 5 of 9

Default Parameters

Provide optional values with defaults at the end of a parameter list.

Lesson

A default parameter lets callers omit an optional argument. Required parameters should come before optional ones, and defaults should be simple, predictable values. Avoid a default that disguises a missing required business decision; validate important choices explicitly. Callers can use the default or override it when a different value is appropriate. Further guidance Treat a function as a small contract: name its inputs, state what it returns, and avoid hidden dependencies. Test a representative value and an edge case. Keep a function focused; callers should decide how to display a returned result or handle a reported failure. Practice task: Create a fresh example for Default Parameters. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Default Parameters
PHP
function greet(string $name, string $salutation = 'Hello'): string
{
    return "$salutation, $name";
}
echo greet('Sam');
Expected output
Hello, Sam

Key points

  • Provide optional values with defaults at the end of a parameter list.
  • Keep inputs, return values, and side effects explicit.
  • Prefer focused functions that are easy to test independently.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.