PHP7 Type Hinting And Docblocks

Among the awesome improvements brought to us by PHP7, comes type hinting. An addition to PHP which might be controversial among developers who love PHP’s dynamic typing. PHP isn’t losing its flexibility. On the contrary, we are now gaining yet another way to express our intentions in our code.

Type-hinting shouldn’t be applied everywhere without reason, because it does come with a small performance hit, since type checks are added at runtime. Some specific reasons to use type hinting include:

  • Improve readability of code that is used by many developers.
  • Lock-in types to force the use of the code as intended.
  • Improve integrity of critical code.
  • When PHP’s dynamic casting would cause problems or require extra checks.
  • To simplify the use of code that will be shared with others.
  • To protect & self-document ‘black-box’ type components and code that is encoded or otherwise source-unavailable.
  • Simplify testing.
  • To provide an extra layer to validate untrusted or user submitted data.

Let’s see how a simple function differs without and with type hinting.

WITH Docblocks

Without type hinting, developers can show the intention of their code with specifically formatted comments. Docblocks have their uses, but a large part of what makes them valuable is to indicate the parameter and return types used by a function or method. Information which is otherwise difficult to determine. Even my short function here, has a large comment:

/**
 * Prepare a cup of get-stuff-done.
 * @param CoffeeBean $beans An amount of coffee beans.
 * @param int $cream A number of teaspoons of cream.
 * @param int $sugar A number of teaspoons of sugar.
 *
 * @return bool Whether we successfully made coffee.
 */
public function makeCoffee($beans, $cream, $sugar){
  $ground = $this->grind($beans);
  $this->brew($ground);
  $this->add([$cream, $sugar]);
  return true;
}

With PHP7 Type Hinting

With type hinting, we can eliminate a large chunk of redundant docblocks. With a bit of an improvement to our parameter names we complete the self-documenting and make our code shorter and clearer. No more need to keep comments and code in sync. And our code now enforces the types instead of relying on the developer to read and obey the docblock. Nice!

/**
 * Prepare a cup of get-stuff-done.
 */
public function makeCoffee(CoffeeBean $beans, int $creamTsp, int $sugarTsp): bool{
  $ground = $this->grind($beans);
  $this->brew($ground);
  $this->add([$creamTsp, $sugarTsp]);
  return true;
}

Conclusion

Use type hinting when it improves your application or makes sense for you. In most cases the small effect on performance won’t matter, and you’ll enjoy the many benefits.

Learn more: PHP.net Type Declarations.

One thought on “PHP7 Type Hinting And Docblocks

Leave a Reply

Your email address will not be published. Required fields are marked *