Lesson 5 of 8 · 9 min

Typed functions

PHP functions can declare the types of their parameters and their return value:

<?php
declare(strict_types=1);

function area(float $width, float $height): float {
    return $width * $height;
}

echo area(2.5, 4);        // 10
echo area("big", 4);      // TypeError: must be of type float, string given

declare(strict_types=1); at the very top (straight after <?php) tells PHP to refuse wrong types instead of quietly converting them. Most modern PHP code turns it on.

Common types: int, float, string, bool, array, a class name, and ?string for "a string or null". A function that returns nothing has the return type void.

Defaults and named arguments

function greet(string $name, string $greeting = "Hello"): string {
    return "$greeting, $name!";
}

greet("Ana");                       // Hello, Ana!
greet("Ana", "Mhoro");              // Mhoro, Ana!
greet(greeting: "Bonjour", name: "Ana");   // named arguments, in any order

Named arguments (PHP 8) make calls with many options readable, and let you skip the ones you do not need.

Arrow functions

Short anonymous functions use fn:

$double = fn($n) => $n * 2;
echo $double(4);   // 8

Your task

Write formatPrice(float $amount, string $currency = "USD"): string, returning e.g. "USD 12.50". Turn on strict types, so that formatPrice("abc") fails with a TypeError.

index.php
<?php
function formatPrice($amount, $currency) {
}

echo formatPrice(12.5, "USD"), "\n";

PHP 8.4 runs right here in your browser. The first run downloads about 12 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…