Type hinting in PHP
Type-hinting allows you to enforce specific types in your code. The code below tells the script to enforce strict types:
Note: The strict_types declaration must be the very first statement in the script.
As of PHP 8.0, PHP has thirteen different types you can specify for declarations in your code. Let's take a look at each of them below:
- string - Value must be a string.
- int - Value must be an integer.
- float - Value must be a floating-point number.
- bool - Value must be Boolean (i.e., either true or false).
- array - Value must be an array.
- iterable - Value must be an array or object that can be used with the foreach loop.
- callable - Value must be a callable function.
- parent - Value must be an instance of the parent to the defining class. This can only be used on class and instance methods.
- self - Value must be either an instance of the class that defines the method or a child of the class. This can only be used on class and instance methods.
- interface name - Value must be an object that implements the given interface.
- class name - Value must be an instance of the given class name.
- mixed - Value can be any type.
- void - Value must be nothing. It can only be used in function returns.
Type-Hinting Function Parameters
Type-Hinting Function Returns
Sometimes, you might not want to return anything from a function; if you would like to enforce this, you can use the void type:
Alternatively, you might want to return the instance of the object that defines a function from the same function. You can use the static type for this purpose:
The code above defines a class, Person, with a function, returnPerson, that returns a Person object.
Nullable Types
Union Types
Type-Hinting Class Properties
The callable Type
Constructor property promotion