typestar

Functions and defaults in PHP

Typed functions whose defaults document the call site.

<?php
function brew(string $drink, string $size = "medium"): string {
    return "$size $drink";
}

function total(float $price, float $tax = 0.08, int $qty = 1): float {
    return round($price * $qty * (1 + $tax), 2);
}

echo brew("latte"), "\n";
echo brew("mocha", "large"), "\n";
echo total(3.50), "\n";
echo total(3.50, 0.0, 4), "\n";

How it works

  1. Parameter and return types make the signature the documentation.
  2. $size = "medium" fills in when the caller stays quiet.
  3. total layers two defaults; callers override only what changes.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
331
Tokens
106
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 1 of 3 in Functions, step 10 of 27 in Language basics.

← Previous Next →