O'Reilly logo

PHP 7 Programming Cookbook by Doug Bierer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hinting at data types

In many cases when developing functions, you might reuse the same library of functions in other projects. Also, if you work with a team, your code might be used by other developers. In order to control the use of your code, it might be appropriate to make use of a type hint. This involves specifying the data type your function expects for that particular parameter.

How to do it...

  1. Parameters in functions can be prefixed by a type hint. The following type hints are available in both PHP 5 and PHP 7:
    • Array
    • Class
    • Callable
  2. If a call to the function is made, and the wrong parameter type is passed, a TypeError is thrown. The following example requires an array, an instance of DateTime, and an anonymous function:
    function someTypeHint(Array ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required