Zend PHP 7 Certification – Functions – Returns

This post covers the Returns section of the Functions chapter when studying for the Zend PHP 7 Certification.

Return calls within a function end its execution immediately and pass control back to the line from which it was called. Any data type can be returned, and if a return statement is omitted, then NULL is returned.

<?php
function addNumbers($num1, $num2) {
    return $num1 + $num2;
}

echo addNumbers(4, 5);   // Outputs: 9

return cannot return multiple values, so if you need to do so, return an array.

<?php
function getList() {
    return ['apples', 'banana', 'pear'];
}

print_r(getList()); // Outputs: Array ( [0] => apples [1] => banana [2] => pear )

As of PHP version 7.0, support has been added for return type declarations, which specify the type of value that will be returned from a function.

<?php
function addNumbers($num1, $num2): float {
    return $num1 + $num2;
}

var_dump(addNumbers(1, 2)); // Outputs: float(3)

By default, return type declarations are in a weak mode. This means that if the return type of the value is not the expected type, PHP will try and correct it.

In strong mode, if the return type of the value is not the expected type, a TypeError will be thrown.

To declare strong mode, use the declare keyword specifying the strict type.

<?php
declare(strict_types=1);

function addNumbers($num1, $num2): int {
    return $num1 + $num2;
}

var_dump(addNumbers(1, 2)); // Outputs: int(3)
var_dump(addNumbers(1, 2.5)); // Fatal error: Uncaught TypeError: Return value of addNumbers() must be of the type integer, float returned

PHP 7.1 allows for void and null return types.

Functions declared with void are declared by preceding the type declaration with a void keyword. Their return type must either omit their return statement altogether, or use an empty return statement. NULL is not a valid return value for a void function.

<?php
function addNumbers($num1, $num2): void {
    return;
}

Functions declared with null are declared by preceding the type declaration with a ?. This indicates that as well as the specified type, NULL can be returned as a value.

<?php
function testReturn(): ?string {
    return 'test';
}

function testReturn(): ?string {
    return null;
}

View the other sections:

Note: This article is based on PHP version 7.1.