Recently Union Types version 2.0 was accepted for PHP 8.0. It will be a cool feature for the next version of PHP. In this post, I'll be discussing the good and the bad of it.
Introduction to Type Declarations
In PHP, type declaration has two usages.
// in functions (argument and return types)
function hello(string $text) : string {
return $text;
}
This code says the $text argument should receive a string (string $text
) and the function should return a string (: string
). This is what we occasionally deal with. Additionally, type declaration for class properties will be available from PHP 7.4.
Currently supported types are: array, callable, int, float, bool, and string.
Type declaration is there for two main purposes.
- Low-level data / Code integrity: it is more difficult to misuse methods and type checking is reduced.
- Code readability: it is clearer what a method accepts and what it will return.
Union Types
Union Types suggests type declaration to have multiple types combined with "OR". For example, one type hint can be string or int
In the current version of PHP, there are two supported union types.
-
Type or null - Use
?
before the type.
function foo(?int $x) {
// ...
}
-
array or Traversable - Use
iterable
.
function loop(iterable $arr) {
// ...
}
Except for these two types, arbitrary union types are not yet supported. If needed, we have to use laggy PHPDoc annotations as following.
/**
* @param int|float $number
*/
function processScore($score) {
return floor($score / 2);
}
Union Types 2.0
- Union Types 2.0 suggests using arbitary union types.
- The syntax format is as simple as
type1|type2|...
. - These can be used in all above mentioned places of type declarations.
The above code can be written as follows.
function processScore(int|float $score) {
return floor($score / 2);
}
The Good
- PHPDoc can be ditched (Unless you use
@throws RandomException
) - Type declarations are more readable.
- New proposal supports the psuedo-type
false
. This is extremely useful for functions that returns false on a failure. ($mysqli -> prepare()
)
Let's discuss your thoughts!
Top comments (0)