Return type declaration
Learn to declare a function's return type with the : type syntax.
Return type
A return type states in the signature which type a function returns. It is written after the closing parenthesis as : type.
Example: function square(int $n): int { return $n * $n; }. Here : int declares the function always returns an integer. return $n * $n; gives an integer so it fits; writing return "text"; would raise a type error.
The void return type
Some functions do not return a value; they only perform a side effect (printing, writing to a file). For these you use the void return type.
Example: function logMsg(string $msg): void { echo $msg; }. Since echo returns nothing, the function returns nothing; : void declares that clearly. A void function can exit early with return; but not with return $x;.
Exercise Square a number
Define a function square with an int $n parameter and a : int return type. In the body write return $n * $n;. Then print the result with echo square(7) . "\n";.
Show example solution
int { ... }, put return $n * $n; in the body, then call with echo square(7) . "\n";.
Example solution:
<?php
// Define square and call it
function square(int $n): int {
return $n * $n;
}
echo square(7) . "\n";
Test yourself
-
Complete the return type
function add(int $a, int $b)____ { return $a + $b; }Show answer
function add(int $a, int $b): int { return $a + $b; } -
What is the output of the following code?
function square(int $n): int { return $n * $n; } echo square(6);- 12
- 36
- 6
- int
Show answer
36 — Correct. 6 * 6 = 36; the : int return type does not change the output.
-
Match return types
- : int
- Returns an integer
- : string
- Returns a string
- : void
- Returns no value