php – Assign type to parameters

Question:

Is it possible to assign types to parameters in functions in PHP?

Example:

public function random(int $length) {
  // ...
}

Answer:

This is partially possible through the so-called type hinting . Can only use complex types such as objects, arrays or callable types ( lambdas ). It is not possible to use scalar types such as int or string which loses much of the advantage.

Still, the support given by the compiler is limited. Remember that language is dynamic and it is not always possible to guarantee everything you want without losing flexibility.

There is information that PHP 7 would have extended this (in fact it happened, especially in 7.4), after all Hack , which is a new competitor, allows the so-called type specification quite broadly (changes the name in PHP as well).

Scroll to Top