CodeBlanks Logo Icon CodeBlanks

Typed parameters

PHP course · Beginner · Lesson 80/116

Learn to declare a parameter's type (int, string, array) and get an error on wrong types.

Type declaration

A type declaration states in the function signature which type a parameter accepts. The type is written before the parameter name.

Example: function add(int $a, int $b) { return $a + $b; }. Here int $a and int $b accept only integers. The call add(5, 3) works and returns 8; passing an incompatible type throws a TypeError.

int, string and array types

Common PHP parameter types are int (integer), string and array. The type is written before the parameter name.

Examples: function double(int $n) expects an integer; function printLabel(string $label) expects a string; function sum(array $items) expects an array. Passing the wrong type throws a TypeError, so mistakes are caught early at the call site.

Exercise Double a number

Define a function double with an int $n parameter. In the body write return $n * 2;. Then print the result with echo double(21) . "\n";.

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

Test yourself

  1. Which one is a typed function?

    • function add($a, $b) { ... }
    • function add(a, b) { ... }
    • function add(int, int) { ... }
    • function add(int $a, int $b) { ... }
    Show answer

    function add(int $a, int $b) { ... } — Correct. int $a and int $b declare the parameter types.

  2. Complete the type declaration

    function printLabel(____) { echo $label; }
    Show answer
    function printLabel(string $label) { echo $label; }
  3. Match type declarations

    int $n
    Integer parameter
    string $label
    String parameter
    array $items
    Array parameter

All lessons in Beginner