CodeBlanks Logo Icon CodeBlanks

Summary - Parameters

PHP course · Beginner · Lesson 82/116

Build a safe calculation function with parameters, defaults and type declarations.

Summary - Parameters

In this group you learned parameterized functions: single parameter, default value, multiple parameters, type declarations and return types.

A safe calculation signature looks like function calculateTotal(float $price, int $qty = 1): float. Here float $price and int $qty declare types, $qty = 1 gives a default, and : float guarantees the return type. Together these build error-free, reusable functions.

Exercise Calculate a safe total

Define a function calculateTotal with parameters float $price and int $qty = 1 and a : float return type. In the body write return $price * $qty;. Then print the result with echo calculateTotal(50, 2) . "\n";.

Show example solution
float { ... }, put return $price * $qty; in the body, then call with echo calculateTotal(50, 2) . "\n";.
Example solution:
<?php
// Define calculateTotal and call it
function calculateTotal(float $price, int $qty = 1): float {
    return $price * $qty;
}
echo calculateTotal(50, 2) . "\n";

Test yourself

  1. Which is a safe calculation function signature?

    • function calculateTotal(float $price, int $qty = 1): float { ... }
    • function calculateTotal($price, $qty) { ... }
    • function calculateTotal(float $price): int { ... }
    • function calculateTotal(int $price = 1, float $qty): float { ... }
    Show answer

    function calculateTotal(float $price, int $qty = 1): float { ... } — Correct. Types are declared, $qty has a default and the return type is float.

  2. Complete the function header

    function calculateTotal(float $price____): float { return $price * $qty; }
    Show answer
    function calculateTotal(float $price, int $qty = 1): float { return $price * $qty; }
  3. Which statement about this group is true?

    • A parameter with a default cannot be skipped.
    • Type declaration is only for return types.
    • Multiple parameters are separated by commas.
    • The return type : type is written before the parameter parentheses.
    Show answer

    Multiple parameters are separated by commas. — Correct. Multiple parameters are separated by commas: function f($a, $b).

All lessons in Beginner