PHP 8 News: Union Types and Mixed Types

Antonio Silva - Feb 3 - - Dev Community

Union Types

PHP 8 introduced Union Types as a significant improvement in how we can declare data types in PHP. Prior to PHP 8, type declaration was limited to a single type or allowed only for the acceptance of null (using the ? operator). With Union Types, it's now possible to specify that a variable can have one of several different types.

The basic syntax for declaring Union Types involves using the vertical bar (|) between the desired types. Here's a simple example:

function sum(int|float $number): int|float {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

In this example, the sum function accepts a parameter $number that can be of type int or float, and the function can return a value of type int or float.

Union Types are useful when working with nullable values. Prior to PHP 8, you would use ?Type to indicate that a variable could be of type Type or null. Now, with Union Types, you can use Type|null to express the same idea more explicitly.

function sum(?int $value): int|null {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Union Types, improving code readability, facilitating maintenance, and making type checking more robust. This is especially useful in large projects or situations where type clarity and precision are crucial.

Mixed Types

The mixed type is a dynamic and flexible way to handle variables whose types may change during the execution of a script. It essentially allows a variable to hold values of any type without imposing strict type constraints.

function processValue(mixed $data): mixed {
    // Code to process $data
}
Enter fullscreen mode Exit fullscreen mode

In this example, the processValue function accepts a parameter $data of type mixed, and it can return a value of any type (mixed).

Beware that excessive use of mixed can diminish the benefits of strong typing and impair the ability of static analysis tools to detect possible errors. It is generally recommended to prefer more specific types when possible and to reserve the use of mixed for situations where the type cannot be precisely determined.

It's worth noting that mixed is implicitly used when a type declaration is omitted or when the @var PHPDoc annotation is used without specifying a type.

// Implicit use of mixed when type declaration is omitted
function exampleFunction($variable) {
    // $variable is of type mixed
}

/** @var mixed $dynamicVariable */
$dynamicVariable = getDynamicValue();
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .