Default Argument Values
What Is a Default Argument Value? In simple terms: A default value is the value a parameter uses when the caller does not pass an argument for it. It makes that parameter optional . Technically: In a
What Is a Default Argument Value?
In simple terms: A default value is the value a parameter uses when the caller does not pass an argument for it. It makes that parameter optional.
Technically: In a function declaration, a parameter can be followed by = and a constant expression. If the corresponding argument is omitted in a call, PHP assigns the default expression's value to the parameter.
Why Defaults Are Useful
Many functions have settings that are the same in most calls: a currency symbol, a number of decimal places, a page size, a sort order. Defaults let common calls stay short while still allowing special cases:
formatAmount(1499); // uses the usual settings
formatAmount(1499, 0, '$'); // overrides them when needed
Syntax
function functionName(Type $required, Type $optional = defaultValue)
{
// ...
}
Example
<?php
function greet(string $name, string $greeting = 'Hello'): string
{
return "$greeting, $name!";
}
echo greet('Asha') . "\n";
echo greet('Asha', 'Vanakkam') . "\n";
Output
Hello, Asha!
Vanakkam, Asha!
How It Works
$namehas no default, so it is required.$greetinghas the default'Hello', so it is optional.- When the second argument is omitted,
$greetingis'Hello'; when it is passed, the passed value is used.
Several Optional Parameters
<?php
function formatAmount(
float $amount,
int $decimals = 2,
string $symbol = '₹',
bool $showSymbol = true,
): string {
return ($showSymbol ? $symbol : '') . number_format($amount, $decimals);
}
echo formatAmount(1234.5) . "\n";
echo formatAmount(1234.5, 0) . "\n";
echo formatAmount(1234.5, 2, '$') . "\n";
echo formatAmount(1234.5, showSymbol: false) . "\n";
Output
₹1,234.50
₹1,235
$1,234.50
1,234.50
Skipping Optional Parameters
With positional arguments, you cannot skip a parameter in the middle. To change only $symbol, you must also pass $decimals, even though you want its default — as in the third call.
Named arguments (PHP 8.0+) solve this: the fourth call sets only showSymbol and leaves $decimals and $symbol at their defaults. See Named Arguments.
Ordering Optional Parameters
Because positional callers must pass every earlier argument to reach a later one, order optional parameters from most frequently changed to least frequently changed.
What Can Be a Default Value?
A default value must be a constant expression — a value PHP can determine without running your code.
| Allowed | Example |
|---|---|
| Literals | = 10, = 'INR', = true, = 2.5 |
null | = null |
| Arrays | = [], = ['asc', 'desc'] |
| Constants and class constants | = PHP_EOL, = self::DEFAULT_LIMIT |
| Constant expressions | = 60 * 60, = 'v' . 2 |
| Enum cases (PHP 8.1+) | = Status::Active |
new expressions (PHP 8.1+) | = new NullLogger() |
| Not Allowed | Example |
|---|---|
| Function calls | = time(), = date('Y') |
| Variables | = $defaultLimit |
Example of an Invalid Default
<?php
function logEvent(string $event, int $timestamp = time())
{
// ...
}
Result
PHP Fatal error: Constant expression contains invalid operations
The Workaround: null as "Not Provided"
<?php
function logEvent(string $event, ?int $timestamp = null): string
{
$timestamp ??= time();
return date('Y-m-d H:i', $timestamp) . " $event";
}
echo logEvent('Order created', 1791545400) . "\n";
Output (the timestamp shown is in UTC)
2026-10-09 11:30 Order created
nullis used as a marker meaning "the caller did not provide a value".$timestamp ??= time();calculates the real default inside the function — at runtime, on each call.- Callers can still pass their own timestamp, as in the example. (
date()uses the configured timezone; the output assumes UTC.)
Defaults Are Evaluated on Every Call
In PHP, each call receives a fresh default value. Modifying a default array or object inside the function does not affect later calls:
<?php
function addTag(string $tag, array $tags = []): array
{
$tags[] = $tag;
return $tags;
}
print_r(addTag('php'));
print_r(addTag('mysql'));
Output
Array
(
[0] => php
)
Array
(
[0] => mysql
)
Each call starts with a new empty array. (Developers coming from Python, where mutable defaults are shared between calls, sometimes worry about this — PHP does not have that problem.)
Nullable Parameters With null Defaults
When null is a valid input, declare the parameter type as nullable with ? (or |null):
<?php
function searchProducts(string $query, ?string $category = null): string
{
if ($category === null) {
return "Searching '$query' in all categories";
}
return "Searching '$query' in $category";
}
echo searchProducts('lamp') . "\n";
echo searchProducts('lamp', 'Furniture') . "\n";
Output
Searching 'lamp' in all categories
Searching 'lamp' in Furniture
Version note: Older code often wrote
string $category = null(without?). That implicitly made the type nullable. Since PHP 8.4, this is deprecated ("Implicitly marking parameter $category as nullable is deprecated, the explicit nullable type must be used instead"). Always write?string $category = null.
Optional Parameters Must Come Last
Required parameters should come before optional ones:
<?php
function makePayment(string $currency = 'INR', float $amount)
{
// ...
}
Result (PHP 8.1 and newer)
PHP Deprecated: Optional parameter $currency declared before required parameter $amount is implicitly treated as a required parameter
Because $amount is required, a caller must pass something for $currency anyway to reach $amount positionally — so the default can never be used. PHP treats $currency as required and warns about the misleading declaration.
Fix: Put required parameters first: function makePayment(float $amount, string $currency = 'INR').
Choosing Good Defaults
- The most common case: the default should be what most callers want, so typical calls stay short.
- Safe behavior: prefer defaults that are safe if forgotten — for example,
bool $sendEmail = falsefor an action with external effects, or HTML escaping enabled by default. - No surprises: avoid defaults that depend on hidden state; when a value must be computed at runtime, use the
null-and-??=pattern so the behavior is visible in the function body. - Few optional booleans: several optional
boolparameters lead to calls likef($x, true, false, true). Prefer named arguments, separate functions, or an enum.
Practical Example: Building URLs
<?php
function buildUrl(
string $path,
array $query = [],
bool $absolute = false,
string $baseUrl = 'https://gocourse.in',
): string {
$url = ($absolute ? rtrim($baseUrl, '/') : '') . '/' . ltrim($path, '/');
if ($query !== []) {
$url .= '?' . http_build_query($query);
}
return $url;
}
echo buildUrl('/courses') . "\n";
echo buildUrl('courses', ['level' => 'beginner', 'page' => 2]) . "\n";
echo buildUrl('/courses/php', absolute: true) . "\n";
Output
/courses
/courses?level=beginner&page=2
https://gocourse.in/courses/php
Step-by-Step Explanation
- Only
$pathis required; everything else has a sensible default. ltrim($path, '/')and the added'/'guarantee exactly one leading slash, whether or not the caller included one.- The query string is added only when
$queryis not empty, usinghttp_build_query()to encode the values safely. - With
absolute: true, the base URL is prepended. Named arguments let the caller skip$querywithout writing[].
Common Mistakes
Using Function Calls or Variables as Defaults
Effect: Fatal error "Constant expression contains invalid operations".
Fix: Default to null and compute the value inside the function.
Optional Parameters Before Required Ones
Effect: The default can never be used; PHP emits a deprecation notice.
Fix: Put required parameters first.
Implicitly Nullable Parameters
Effect: Deprecation notices in PHP 8.4+.
Fix: Write ?Type $param = null.
Passing null to Get the Default
Effect: For a non-nullable parameter, passing null causes a TypeError; for a nullable one, null is used instead of the default.
Fix: Omit the argument (or use named arguments to skip it) to get the default.
Too Many Optional Parameters
Effect: Callers pass long lists of placeholder values to reach the one they want to change.
Fix: Use named arguments, split the function, or group options into an object.
Best Practices
- Give optional parameters defaults that match the most common use.
- Place required parameters first, then optional ones ordered by how often they change.
- Use explicit nullable types (
?string $x = null) whennullmeans "not provided". - Compute runtime defaults inside the function with
??=. - Combine defaults with named arguments so callers can skip parameters clearly.
Official reference: https://www.php.net/manual/en/functions.arguments.php#functions.arguments.default