← 返回课程: PHP from scratch

Functions: parameters, return values and types

视频即将上线

A function is a named block of code that you can reuse. Instead of copying and pasting the same calculation in ten places, you write it once, give it a name and call it whenever you need it. If one day the rule changes (for example, the tax rate), you fix it in a single place. Functions also split a big problem into small pieces that can be understood and tested separately. It is the most important organizing tool in any language.

Declaring and calling a function

You declare it with the function keyword, the name, the parameters in parentheses and the body in braces. With return you give back a value and the function ends at that point. A parameter is the variable that appears in the declaration; an argument is the concrete value you pass when calling it. Use English names in camelCase (calculateTax) that describe an action. Always declare parameter and return types: with strict_types on, PHP rejects wrong values instead of silently converting them.

php
<?php

declare(strict_types=1);

function addTax(float $price, float $rate = 0.21): float
{
    return round($price * (1 + $rate), 2);
}

echo addTax(100.0), "\n";         // 121
echo addTax(100.0, 0.10), "\n";   // 110

function printLine(string $text): void
{
    echo $text, "\n";             // void: no return value
}

printLine('Done');

try {
    echo addTax('100');           // string given to float
} catch (TypeError $e) {
    echo "Type error caught\n";   // strict_types rejects it
}

Default values, named arguments and variadics

A parameter with a default value is optional; optional ones go last. Since PHP 8 you can pass arguments by name, in any order, which makes calls more readable when there are several booleans or optional values. With three dots (...) you declare a variadic parameter that collects all remaining arguments into an array. If a function may have no result, use a nullable type such as ?int and return null; the caller must check that case before using the value.

php
<?php

declare(strict_types=1);

function formatName(string $first, string $last, bool $upper = false, string $sep = ' '): string
{
    $full = $first . $sep . $last;
    return $upper ? strtoupper($full) : $full;
}

echo formatName('Ana', 'Lima'), "\n";                    // Ana Lima
echo formatName('Ana', 'Lima', sep: ', '), "\n";          // Ana, Lima
echo formatName(last: 'Lima', first: 'Ana', upper: true), "\n"; // ANA LIMA

function sum(int ...$numbers): int
{
    return array_sum($numbers);
}
echo sum(1, 2, 3, 4), "\n";   // 10
echo sum(), "\n";             // 0

function findIndex(array $items, string $needle): ?int
{
    $pos = array_search($needle, $items, true);
    return $pos === false ? null : $pos;
}
var_dump(findIndex(['a', 'b'], 'b')); // int(1)
var_dump(findIndex(['a', 'b'], 'z')); // NULL

Several results and recursion

A function can only return one value, but that value can be an array with several pieces of data. If the array has meaningful keys, the caller reads it clearly. A function can also call itself: that is recursion. It always needs a base case that stops the calls; without it, the program runs out of memory. Recursion is useful for nested structures, such as an array inside another, but a loop is usually simpler and faster when it is enough.

php
<?php

declare(strict_types=1);

/** @return array{min: int, max: int, avg: float} */
function stats(array $numbers): array
{
    return [
        'min' => min($numbers),
        'max' => max($numbers),
        'avg' => array_sum($numbers) / count($numbers),
    ];
}

$result = stats([4, 8, 6]);
echo "min={$result['min']} max={$result['max']} avg={$result['avg']}\n";
// min=4 max=8 avg=6

function factorial(int $n): int
{
    if ($n <= 1) {
        return 1;               // base case
    }
    return $n * factorial($n - 1);
}
echo factorial(5), "\n";        // 120

检验所学

第 1 / 1

What is a base case for in a recursive function?

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →