Adding Return Type Hints

Adding return type hints makes your code better and lets your code document itself

Posted by Alexander Mills on 26 November 2018

It's really useful to know what Type of variable a method or function will return, and it's been done in PHPDoc blocks for years

/**
 * @param string $name 
 *
 * @return string
 */
public function sayHello($name) {
    return 'Hello ' . $name; 
}

This is great, as long as it is correct - its really easy when refactoring of viewing a diff of some code to miss that the return type has changed in the code, but not the PHPDoc.

A really simple way of enforcing that your return type will be correct is to define it as a PHP return Type Hint

public function sayHello(string $name): string {
    return 'Hello ' . $name;
}

Not only does this enforce the type of variables that we are returning, it's also self-documenting, therefore the old PHPDoc is now unecessary.