CodeBlanks Logo Icon CodeBlanks

Named arguments

PHP course · Expert · Lesson 39/54

Learn named arguments that pass values by parameter name.

Named arguments

PHP 8.0 added named arguments: pass a value by its parameter name, e.g. send_email(to: "alex@example.com", subject: "Hello").

You can skip parameters that have defaults: send_email(to: $x, html: true) skips subject, which keeps its default.

Because names are explicit, call order no longer matters and the call documents itself. This is especially useful with long parameter lists.

The nullsafe operator (?->)

PHP 8.0 added the ?-> operator: if the left side is null, it returns null instead of throwing. It makes chained access safe.

For example $user?->profile?->avatar: if $user or profile is null, the whole expression is null; no NullPointerException.

It is read-only; you cannot assign through it. Combine with ?? to supply a default value.

Exercise Fetch avatar with nullsafe

Define user_avatar(?User $u): string. Use the chain $u?->profile?->avatar to read the avatar; fall back to ?? "default.png".

The call below uses user: null and should print default.png.

Show example solution
class Profile {
  public string $avatar = "me.png";
}

class User {
  public ?Profile $profile = null;
}

function user_avatar(?User $u): string {
  return $u?->profile?->avatar ?? "default.png";
}

echo user_avatar(user: null);

Test yourself

  1. Named arguments concepts

    name:
    pass by parameter name
    ?->
    null-safe access
    skip
    defaulted params skipped
    by name
    order no longer matters
  2. Write the nullsafe operator

    $avatar = $user____->profile->avatar;
    
    Show answer
    $avatar = $user?->->profile->avatar;
    
  3. Which call enables HTML mode?

    function send_email(string $to, string $subject = "Hi", bool $html = false) {}
    • send_email(to: "a@b.com", html: true)
    • send_email("a@b.com", true)
    • send_email(to: "a@b.com",, true)
    • send_email(html: true)
    Show answer

    send_email(to: "a@b.com", html: true) — Correct. subject keeps its default and html: true enables HTML mode.

All lessons in Expert