Named Arguments

Pass arguments by parameter name instead of position — skip optional ones, and make call sites self-documenting.

Named arguments let you say which parameter you're filling: foo(limit: 10). Two big wins follow. You can skip any optional parameters before the one you care about, and a call like createUser(active: false, admin: true) documents itself — no more guessing what a bare true, false, true means.

Easy example

<?php
function connect(string $host, int $port = 5432, bool $ssl = true) {
    return "$host:$port ssl=" . ($ssl ? 'on' : 'off');
}
// skip $port, set only $ssl
echo connect('db.local', ssl: false);

You can mix positional and named, as long as positional ones come first. Named arguments also pair perfectly with ...$args spreading of associative arrays.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Call array_slice with named arguments to skip the $preserve_keys parameter and make the intent obvious.
  • Use named args to pass only the $separator and $limit to explode, skipping optional parameters cleanly.
  • Self-document a complex htmlspecialchars() call by naming the $flags and $encoding arguments.

More examples

Skipping optional parameters

Named arguments let you skip optional parameters you don't need, removing the need for placeholder null values.

Example · php
<?php
$items = ['a', 'b', 'c', 'd', 'e'];

// Without named args: must pass all preceding args
$slice1 = array_slice($items, 1, 3, true);

// With named args: skip $length, set only $preserve_keys
$slice2 = array_slice($items, offset: 1, preserve_keys: true);

print_r($slice2);

Self-documenting function calls

Naming the flags and encoding arguments makes the call self-explanatory without needing a comment.

Example · php
<?php
$html = htmlspecialchars(
    string:  '<script>alert(1)</script>',
    flags:   ENT_QUOTES | ENT_HTML5,
    encoding: 'UTF-8'
);

echo $html; // &lt;script&gt;alert(1)&lt;/script&gt;

Named args in user-defined functions

Named arguments work with user-defined functions; you can reorder them and skip intermediate optional ones.

Example · php
<?php
function createTag(string $tag, string $content, string $class = '', string $id = ''): string {
    $attrs  = $class ? " class=\"$class\"" : '';
    $attrs .= $id    ? " id=\"$id\""       : '';
    return "<$tag$attrs>$content</$tag>";
}

// Skip $class, set only $id
echo createTag(tag: 'p', content: 'Hello', id: 'intro');
// <p id="intro">Hello</p>

Discussion

  • Be the first to comment on this lesson.