Named and optional parameters

suggest change

A PHP function can give a parameter a default value, which makes the parameter optional: the caller can leave it out. Since PHP 8.0 the caller can also pass arguments by name instead of by position, so it can skip optional parameters it doesn't care about and make calls easier to read.

This article covers both features, how they work together, the rules and errors to know about, and the deprecations that PHP 8.x added around them. All examples were run with PHP 8.5.

For the basics of functions see Functions. For ...$args see Variadic parameters.

Default values

Give a parameter a default with = value. If the caller doesn't pass that argument, the default is used:

<?php
function greet(string $name, string $greeting = 'Hello', string $punct = '!'): string
{
    return "$greeting, $name$punct";
}

echo greet('Alice'), "\n";
echo greet('Bob', 'Hi'), "\n";
echo greet('Carol', 'Welcome', '.'), "\n";

Output:

Hello, Alice!
Hi, Bob!
Welcome, Carol.

A default must be a constant expression: literals, arrays, null, constants, class constants and arithmetic on them. You can't call a function or use a variable:

<?php
const DEFAULT_PORT = 5432;

class Db
{
    public const TIMEOUT = 30;
}

function connect(
    string $host = 'localhost',
    int $port = DEFAULT_PORT,
    int $timeout = Db::TIMEOUT * 2,
    array $options = ['ssl' => true],
    ?string $user = null,
): void {
    echo "$host:$port timeout=$timeout ssl=", var_export($options['ssl'], true),
        " user=", $user ?? '(none)', "\n";
}

connect();
connect('db.example.com', 6432);

Output:

localhost:5432 timeout=60 ssl=true user=(none)
db.example.com:6432 timeout=60 ssl=true user=(none)

Note the trailing comma after the last parameter. It's allowed since PHP 8.0 and makes long parameter lists easier to edit.

Defaults are evaluated on every call

Unlike Python, PHP doesn't share one default value between calls. An array default is a fresh array each time, so you can modify it safely:

<?php
function addItem(string $item, array $list = []): array
{
    $list[] = $item;
    return $list;
}

print_r(addItem('a'));
print_r(addItem('b'));

Output:

Array
(
    [0] => a
)
Array
(
    [0] => b
)

Objects as defaults with new

Since PHP 8.1 a default can create an object with new. A new object is created on each call where the argument is missing:

<?php
class Logger
{
    public static int $created = 0;

    public function __construct(public string $prefix = 'app')
    {
        self::$created++;
    }
}

function handle(string $msg, Logger $logger = new Logger()): void
{
    echo "[{$logger->prefix}] $msg\n";
}

handle('first');
handle('second');
handle('third', new Logger('custom'));
echo "Loggers created: ", Logger::$created, "\n";

Output:

[app] first
[app] second
[custom] third
Loggers created: 3

Before 8.1 the usual workaround was ?Logger $logger = null followed by $logger ??= new Logger(); inside the function. That pattern still works and is still useful when building the default takes more than one expression.

Rules for declaring optional parameters

Optional parameters go last

With positional arguments, you can only leave out arguments from the end. A parameter with a default that comes before a required one can never actually be omitted, so PHP treats it as required and emits a deprecation warning:

<?php
function bad(string $table = 'users', int $id): string
{
    return "$table#$id";
}

echo bad('posts', 7), "\n";

Output (file path shortened):


Deprecated: bad(): Optional parameter $table declared before required parameter $id is implicitly treated as a required parameter in /path/to/05.php on line 2
posts#7

Move required parameters to the front, or remove the useless default.

Use explicit nullable types

Old code often wrote string $color = null to mean "a string or null". A null default used to make the type nullable implicitly. This is deprecated since PHP 8.4:

<?php
function label(string $text, string $color = null): string
{
    return $text . ' ' . ($color ?? 'default');
}

echo label('x'), "\n";

Output (file path shortened):


Deprecated: label(): Implicitly marking parameter $color as nullable is deprecated, the explicit nullable type must be used instead in /path/to/06.php on line 2
x default

The fix is to write the nullable type out: ?string $color = null (or string|null $color = null). See Nullable type hints.

The problem named arguments solve

With positional arguments only, using the 4th parameter means passing the 2nd and 3rd too, even if you want their defaults. htmlspecialchars() is a classic case. Its signature is htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true):

<?php
$s = 'Tom &amp; Jerry <3';

// Default: & is encoded again, giving &amp;amp;
echo htmlspecialchars($s), "\n";

// Before PHP 8: repeat every default just to reach $double_encode
echo htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, null, false), "\n";

// PHP 8+: name the one argument you care about
echo htmlspecialchars($s, double_encode: false), "\n";

Output:

Tom &amp;amp; Jerry &lt;3
Tom &amp; Jerry &lt;3
Tom &amp; Jerry &lt;3

Copying defaults by hand is error-prone: if you get one of them wrong, or the default changes in a later PHP version, your code silently behaves differently. The named version only says what's different from the defaults.

Named arguments

Write the parameter name (without $), a colon and the value. Named arguments can come in any order, and any optional parameter you don't name gets its default:

<?php
function createUser(string $name, string $role = 'user', bool $active = true, ?string $email = null): string
{
    return sprintf('%s role=%s active=%s email=%s',
        $name, $role, $active ? 'yes' : 'no', $email ?? '-');
}

// All named, any order
echo createUser(email: 'ann@example.com', name: 'Ann'), "\n";

// Positional first, then named
echo createUser('Bob', active: false), "\n";

// Skip $role and $active entirely
echo createUser('Cid', email: 'cid@example.com'), "\n";

Output:

Ann role=user active=yes email=ann@example.com
Bob role=user active=no email=-
Cid role=user active=yes email=cid@example.com

Named arguments also make boolean flags readable. Compare createUser('Bob', 'user', false) with createUser('Bob', active: false): in the first one you have to look up the signature to know what false means.

Errors

PHP checks named arguments when the function is called:

<?php
function f(int $a, int $b = 2, int $c = 3): string
{
    return "$a $b $c";
}

$calls = [
    'f(1, c: 30, b: 20)' => fn() => f(1, c: 30, b: 20),
    'f(1, a: 10)'        => fn() => f(1, a: 10),
    'f(1, d: 4)'         => fn() => f(1, d: 4),
    'f(b: 5)'            => fn() => f(b: 5),
];
foreach ($calls as $label => $call) {
    try {
        $result = $call();
    } catch (Error $e) {
        $result = get_class($e) . ': ' . $e->getMessage();
    }
    echo str_pad($label, 19), '=> ', $result, "\n";
}

Output:

f(1, c: 30, b: 20) => 1 20 30
f(1, a: 10)        => Error: Named parameter $a overwrites previous argument
f(1, d: 4)         => Error: Unknown named parameter $d
f(b: 5)            => ArgumentCountError: f(): Argument #1 ($a) not passed

Positional arguments must come before named ones. Breaking this rule is a compile-time error, so the whole file fails to run:

<?php
function f(int $a, int $b = 2) {}
f(a: 1, 2);

Output (file path shortened):


Fatal error: Cannot use positional argument after named argument in /path/to/10.php on line 3
Stack trace:
#0 {main}

Named arguments with built-in functions

Every built-in function supports named arguments. The names are the ones shown in the PHP manual. This is where named arguments help the most, because many built-ins have long lists of optional parameters:

<?php
echo str_pad('42', 6, '0', STR_PAD_LEFT), "\n";
echo str_pad('42', length: 6, pad_string: '0', pad_type: STR_PAD_LEFT), "\n";

print_r(array_slice(['a' => 1, 5 => 'x', 9 => 'y'], 1, preserve_keys: true));

echo json_encode(['url' => 'https://example.com/a', 'name' => 'Zoë'],
    flags: JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), "\n";

print_r(array_fill(start_index: 10, count: 3, value: '-'));

var_dump(in_array('1', [1, 2, 3], strict: true));

Output:

000042
000042
Array
(
    [5] => x
    [9] => y
)
{"url":"https://example.com/a","name":"Zoë"}
Array
(
    [10] => -
    [11] => -
    [12] => -
)
bool(false)

array_slice(..., 1, preserve_keys: true) skips $length (default null, meaning "to the end"), which you'd otherwise have to pass as null explicitly. in_array(..., strict: true) documents at the call site that the comparison is strict.

Unpacking arrays into named arguments

The spread operator ... turns an array into arguments. Integer keys become positional arguments and string keys become named arguments. This is handy for merging configuration:

<?php
function connect(string $host, int $port = 3306, string $charset = 'utf8mb4', int $timeout = 10): void
{
    echo "$host:$port charset=$charset timeout=$timeout\n";
}

$defaults = ['host' => 'localhost', 'timeout' => 5];
$overrides = ['host' => 'db.internal', 'port' => 3307];

connect(...array_merge($defaults, $overrides));

// Positional values first, then string keys
connect(...['db1', 'charset' => 'latin1']);

Output:

db.internal:3307 charset=utf8mb4 timeout=5
db1:3306 charset=latin1 timeout=10

The same rules apply as for literal named arguments: an unknown key throws Error: Unknown named parameter, and an integer key after a string key is an error. If the array comes from user input, filter its keys first.

Variadic functions collect unknown names

If a function has a variadic parameter, named arguments that don't match a regular parameter are collected into the variadic array with string keys:

<?php
function tag(string $name, string ...$attrs): string
{
    $html = "<$name";
    foreach ($attrs as $key => $value) {
        $html .= " $key=\"" . htmlspecialchars($value) . '"';
    }
    return "$html>";
}

echo tag('a', href: '/home', class: 'nav-link', title: 'Go home'), "\n";
echo tag('input', type: 'checkbox', checked: 'checked'), "\n";

function dump(...$args): void
{
    var_export($args);
    echo "\n";
}
dump(1, 2, x: 3, y: 4);

Output:

<a href="/home" class="nav-link" title="Go home">
<input type="checkbox" checked="checked">
array (
  0 => 1,
  1 => 2,
  'x' => 3,
  'y' => 4,
)

Note that class works as an argument name even though it's a reserved word. If your variadic function only expects a list, keep this in mind: callers can sneak string keys into it. Use array_values() if you need a pure list.

Callbacks and dynamic calls

Named arguments work with call_user_func(), call_user_func_array() (string keys become names) and closures, including first-class callables created with the connect(...) syntax:

<?php
function f(int $a, int $b = 2, int $c = 3): void
{
    echo func_num_args(), ' args: ', json_encode(func_get_args()), "\n";
}

f(1);
f(1, c: 30);

function connect(string $host, int $port = 3306, int $timeout = 10): string
{
    return "$host:$port timeout=$timeout";
}

echo call_user_func_array('connect', ['host' => 'db1', 'timeout' => 2]), "\n";
echo call_user_func('connect', 'db2', timeout: 3), "\n";

$fn = connect(...);
echo $fn(port: 5000, host: 'db3'), "\n";

Output:

1 args: [1]
3 args: [1,2,30]
db1:3306 timeout=2
db2:3306 timeout=3
db3:5000 timeout=10

When you skip $b with a named argument, PHP fills the gap with its default, so func_get_args() reports 3 arguments for f(1, c: 30).

Named arguments with constructors

Constructors with many optional settings are the best use case for named arguments. Together with constructor property promotion they give you a typed "options object" without a builder class:

<?php
final class HttpClientOptions
{
    public function __construct(
        public readonly string $baseUrl,
        public readonly float $timeout = 5.0,
        public readonly int $retries = 0,
        public readonly bool $verifyTls = true,
        public readonly array $headers = [],
    ) {}
}

$opts = new HttpClientOptions(
    baseUrl: 'https://api.example.com',
    retries: 3,
    headers: ['Accept' => 'application/json'],
);

printf("%s timeout=%.1f retries=%d tls=%s headers=%s\n",
    $opts->baseUrl, $opts->timeout, $opts->retries,
    $opts->verifyTls ? 'on' : 'off', json_encode($opts->headers));

Output:

https://api.example.com timeout=5.0 retries=3 tls=on headers={"Accept":"application\/json"}

Compared to the older "options array" style (new Client(['retries' => 3])), a typo in a name is an immediate error instead of a silently ignored key, and IDEs can autocomplete and type-check every option.

null is not "use the default"

Passing null doesn't mean "use the default". The parameter gets null, and if its type doesn't allow null, the call fails. In this example the caller wants the default page but a custom page size:

<?php
function paginate(int $page = 1, int $perPage = 20): string
{
    return "page=$page perPage=$perPage";
}

try {
    echo paginate(null, 50), "\n";
} catch (TypeError $e) {
    echo strstr($e->getMessage(), ', called', true), "\n";
}

function paginate2(?int $page = null, ?int $perPage = null): string
{
    $page ??= 1;
    $perPage ??= 20;
    return "page=$page perPage=$perPage";
}

echo paginate2(null, 50), "\n";

// e.g. values from a query string where missing keys are null
$query = ['page' => null, 'perPage' => 50];
echo paginate2(page: $query['page'], perPage: $query['perPage']), "\n";

Output:

paginate(): Argument #1 ($page) must be of type int, null given
page=1 perPage=50
page=1 perPage=50

With named arguments, the clean fix for paginate() is paginate(perPage: 50). The ?int $x = null plus ??= pattern of paginate2() is useful when the caller has a value that may or may not be set, and wants the default whenever it's null.

Parameter names are part of the API

Once callers can use names, renaming a parameter is a breaking change, just like reordering parameters is for positional calls. This matters most with inheritance. PHP allows a child class to rename a parameter, but named arguments are resolved against the method that actually runs:

<?php
interface Storage
{
    public function save(string $key, string $value): void;
}

class FileStorage implements Storage
{
    // Parameter renamed from $key to $path
    public function save(string $path, string $value): void
    {
        echo "saving $path\n";
    }
}

function store(Storage $s): void
{
    $s->save(key: 'a.txt', value: 'hello');
}

$s = new FileStorage();
$s->save(path: 'b.txt', value: 'hi');

try {
    store($s);
} catch (Error $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

Output:

saving b.txt
Error: Unknown named parameter $key

store() is written correctly against the Storage interface, yet it fails at runtime. When implementing an interface or overriding a method, keep the parent's parameter names. Psalm reports renamed parameters as ParamNameMismatch.

Some libraries mark functions with a @no-named-arguments docblock tag to tell users (and static analysers) that parameter names are not covered by their backward compatibility promise.

Inspecting parameters with reflection

Reflection tells you which parameters a function has, which are optional, and what their defaults are. This works for built-in functions too, which is a quick way to find the right argument name:

<?php
function connect(string $host, int $port = 3306, ?string $user = null, string ...$flags): void {}

foreach ((new ReflectionFunction('connect'))->getParameters() as $p) {
    printf("#%d \$%-6s optional=%-5s default=%s\n",
        $p->getPosition(),
        $p->getName(),
        $p->isOptional() ? 'yes' : 'no',
        $p->isDefaultValueAvailable() ? var_export($p->getDefaultValue(), true)
            : ($p->isVariadic() ? '(variadic)' : '-'));
}

// Built-in functions have names too
$names = array_map(fn($p) => $p->getName(),
    (new ReflectionFunction('array_slice'))->getParameters());
echo 'array_slice(', implode(', ', $names), ")\n";

Output:

#0 $host   optional=no    default=-
#1 $port   optional=yes   default=3306
#2 $user   optional=yes   default=NULL
#3 $flags  optional=yes   default=(variadic)
array_slice(array, offset, length, preserve_keys)

You can also run php --rf array_slice on the command line to print a function's parameters.

Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents