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: Real World Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.