Return Type Declarations in PHP

PHP 7 now makes it possible to declare return types for your methods. This allows you better control over the data that will be returned from each method in your application.

The types of data you can return include but are not limited to the following.

  • self
  • array
  • callable
  • bool
  • float
  • int
  • string

Apart from the above, you can also specify a type of Object that should be returned by passing the name of the Class or Interface.

Example

First let’s specify the return type for our Calculator class. We do this by specifying the return type after the argument definition by appending a colon “:”, followed by the return type.

This will require the method sum to return the value of a float. If for some reason a different value is returned then you’d get a TypeError exception thrown.

Let’s look at another example that specifies a type of object expected as the return value when requesting the name of a person.

We’ll start by creating a Person class, that relies on a PersonName class for the person’s name.

Strict Typing

Another option you have is to declare strict typing for your classes, which takes you from the default weak mode into a strong mode the forces the correct value to be returned rather then being coerced into the correct value. When the correct value type is not returned or passed, a TypeError exception will be thrown.

Let’s look at an example using strict mode.

You’ll see that we defined it by specifying the document in strict mode at the top. Now when we use it the values returned and passed will have to be either a float or a int, if not a TypeError is thrown.

Now let’s change it up a little and require int’s as the arguments and a int as the return value.

If a float is passed as an argument or returned as a return value, then a TypeError exception will be thrown since a float is not the same as a integer.

Previously you could pass your numbers as a string to a method as well, and PHP would convert it to the correct type prior to processing it. Now with strict typing enabled, the TypeError exception would be thrown in those cases as well.