🎓 A1Learner
🔍
0 of 27 lessons completed

Named Arguments

Named arguments label each value with a parameter name at the call site. The label lets a call give values in any order and skip a value that has a default.

Names let the order change

The definition lists name, city, then job. The call names job first and name last, and the built line still puts each value in its right place.

<?php
function profile($name, $city, $job) {
  echo $name . " lives in " . $city . " and works as " . $job . "\n";
}
profile(job: "teacher", name: "Ana", city: "Paris");

A middle default can be skipped

The greet function has three parameters, and each one has a default. The call names the first and the last, so the middle name keeps its default Guest.

<?php
function greet($greeting = "Hello", $name = "Guest", $punct = "!") {
  echo $greeting . ", " . $name . $punct . "\n";
}
greet(greeting: "Hi", punct: "?");

Positional values come first

The ticket call gives the name as a plain positional value. It then names the meal, and the seat keeps its default.

<?php
function ticket($name, $seat = "A1", $meal = "none") {
  echo $name . " seat " . $seat . " meal " . $meal . "\n";
}
ticket("Ben", meal: "veg");

An unknown name fails

The call uses nme, but the function names its parameter name. No parameter matches the label, so the call fails at once.

<?php
function greet($name) {
  echo "Hello, " . $name . "\n";
}
greet(nme: "Ana");

Example

<?php
function book($guest, $room, $nights = 1, $breakfast = "no") {
  echo $guest . " booked " . $room . " for " . $nights . " nights with breakfast " . $breakfast . "\n";
}
book("Eli", "Double", breakfast: "yes", nights: 2);

Key points

  • A named argument writes the parameter name, then a colon, then the value.
  • The names in a call can appear in a different order from the order in the definition.
  • A parameter with a default can be skipped when the call names the values around it.
  • Positional values come first in a mixed call, and named values follow them.
  • The name in the call must match a parameter name exactly.
  • A call with a name that matches no parameter fails with an error.

In this example, a booking function takes a guest, a room, a night count, and a breakfast flag. The call gives the guest and the room as positional values. It then names the breakfast flag and the night count, so two values are given by name. The printed line shows all four values in their places.

Note

Named arguments make a long call read clearly, because each value carries its own label.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when a call names a parameter that does not exist?