Using return value data typing

PHP 7 allows you to specify a data type for the return value of a function. Unlike scalar type hinting, however, you don't need to add any special declarations.

How to do it...

  1. This example shows you how to assign a data type to a function return value. To assign a return data type, first define the function as you would normally. After the closing parenthesis, add a space, followed by the data type and a colon:
    function returnsString(DateTime $date, $format) : string
    {
      return $date->format($format);
    }

    Note

    PHP 7.1 introduced a variation on return data typing called nullable types. All you need to do is to change string to ?string. This allows the function to return either string or NULL.

  2. Anything returned by the function, ...

Get PHP 7 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.