PHP 8 Beginner Language Basics · 8 min read

PHP Functions, Parameters, Return Types, and Defaults

Lesson 8 of 43 in the PHP 8 learning path.

How do I write a PHP function with a return type?

A function names a calculation, lists the values it needs, and declares the type it returns. letterGrade() takes an int score and an optional string scale that defaults to k12. The return type string means every path has to return a string. With declare(strict_types=1) in this file, a call that passes a numeric string for the score throws TypeError instead of casting it. The default argument is used when the caller omits the scale, and it has to sit after the required parameter.

Inside the function, a score outside 0 through 100 throws InvalidArgumentException, and any scale other than k12 is rejected. A match expression then maps the remaining scores onto A, B, C, or D. Defaults are for values that are truly optional and safe. A passing line or a scale that changes by campus should be an explicit argument so the call site shows the policy.

Syntax & Parameters

Syntax
function letterGrade(int $score, string $scale = 'k12'): string

Example

src/Grades.php
<?php

declare(strict_types=1);

function letterGrade(int $score, string $scale = 'k12'): string
{
    if ($score < 0 || $score > 100) {
        throw new InvalidArgumentException('Score must be between 0 and 100.');
    }
    if ($scale !== 'k12') {
        throw new InvalidArgumentException('This grade book uses the k12 scale.');
    }

    $letter = match (true) {
        $score >= 90 => 'A',
        $score >= 80 => 'B',
        $score >= 75 => 'C',
        default => 'D',
    };

    return $letter . ':' . $scale;
}

echo 'amina=' . letterGrade(92) . "\n";
echo 'luis=' . letterGrade(76) . "\n";
echo 'bea=' . letterGrade(74) . "\n";

try {
    letterGrade(92, 'college');
    echo "college=accepted\n";
} catch (InvalidArgumentException $error) {
    echo 'college=' . $error->getMessage() . "\n";
}

Expected Output

amina=A:k12
luis=C:k12
bea=D:k12
college=This grade book uses the k12 scale.

Line-by-Line Walkthrough

  1. declare(strict_types=1) makes the letterGrade() calls in this file require a real int and a real string.
  2. The signature takes $score first and $scale second, with the default k12 only on the second parameter.
  3. Scores outside 0 through 100 throw InvalidArgumentException before any letter is chosen.
  4. A scale other than k12 throws, so the default is the only scale this function will apply.
  5. match (true) walks the thresholds in order and assigns A at 90, B at 80, C at 75, and D otherwise.
  6. The return concatenates the letter, a colon, and the scale, satisfying the string return type.
  7. letterGrade(92) omits the scale, so the default k12 is used and the line reads amina=A:k12.
  8. Luis at 76 is at least 75 and below 80, so the result is C:k12.
  9. Bea at 74 falls through to the default arm and prints D:k12.
  10. letterGrade(92, "college") hits the scale guard and the catch prints the validation message instead of a letter.

Common Pitfalls & Security

A missing return type lets a function hand back null, an array, or a string depending on the path, and the grade book prints whichever one shows up. A default that hides a required policy makes call sites look alike when they are not. Validation belongs in the function when the rule is part of the calculation, and the message should be safe to show to a teacher.

  • A default parameter followed by a required parameter is a compile error. Put required parameters first.
  • Forgetting a return on one branch is a TypeError once the function declares : string. Every path, including the match default, has to return.
  • match does not fall through. The order of arms matters: testing >= 75 before >= 90 would label a 92 as C.
  • Unsafe anti-pattern (do not ship): letterGrade((int) $_POST["score"]) without checking that the field was numeric. A cast turns "nope" into 0 and awards a D.
  • A default of k12 is visible in the signature. A default that reads a database inside the function hides I/O in a helper that looks pure.
  • Catching TypeError from a bad call and continuing as if the grade existed records a blank result. Validate at the form, then call the function with an int.

Best Practices & Modern Standards

On PHP 8.3, write scalar parameter types, a return type, and declare(strict_types=1) on every function that implements grade-book policy. Use match when the alternatives are exhaustive, and keep the default arm for the remaining scores so a new threshold is a deliberate edit. Throw InvalidArgumentException for values that can never be a grade, and let the form layer turn that into a message.

Keep defaults boring and safe. If a caller must choose a scale, omit the default and make them pass it. Small functions that accept ints and return strings are easy to test without a database, which is the right shape for letter thresholds that teachers will argue about.

Real-World Use

The grade book turns quiz points into letters before the report card is printed. Amina at 92 becomes A:k12, Luis at 76 becomes C:k12, and Bea at 74 becomes D:k12, all through letterGrade() with the default scale. A request that asks for a college scale is rejected with a clear message so the k12 report stays on one policy.

Frequently Asked Questions

Where does the default value come from?

The caller that omits the argument gets the default. letterGrade(92) uses k12 because the signature says string $scale = "k12". letterGrade(92, "college") passes a different string and the function rejects it.

Can a function declare a return type of void?

Yes. void means the function returns nothing useful. letterGrade() returns a string because the report card needs the letter. Use void for actions that only save or send, and a real type when the caller needs a value.

What is the difference between TypeError and InvalidArgumentException?

TypeError is the engine rejecting a value of the wrong type, such as a string passed to an int parameter under strict_types. InvalidArgumentException is your rule rejecting a value of the right type, such as a score of 140 or a scale this book does not use.

Does match require a default arm?

match (true) with range conditions needs a default if some ints are not covered by earlier arms. Without it, an unmatched value throws UnhandledMatchError. The D arm is that default for scores under 75.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…