Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Union Type in PHP 8
PHP 8 introduced Union Types, allowing variables, parameters, and return types to accept values of two or more types instead of a single type. Multiple types are joined using the vertical line (|) operator.
Union types support function parameters, return types, and class properties, providing greater flexibility while maintaining type safety.
Syntax
type1|type2|...|type_n
Basic Union Type Example
Here's a simple class demonstrating union types for properties and methods −
<?php
class Number
{
private int|float $num;
public function getNum(): float|int
{
return $this->num;
}
public function setNum(float|int $num): void
{
$this->num = $num;
}
}
$number = new Number();
$number->setNum(5);
echo "Integer value: " . $number->getNum() . "<br>";
$number->setNum(11.54);
echo "Float value: " . $number->getNum() . "<br>";
?>
Integer value: 5 Float value: 11.54
Nullable Union Types
In PHP 8, nullable types can be declared as type|null instead of the PHP 7.1 syntax ?type. For example, float|int|null is valid, but ?float|int is not allowed −
<?php
function processValue(int|string|null $value): string
{
if ($value === null) {
return "No value provided";
}
return "Value: " . $value;
}
echo processValue(42) . "<br>";
echo processValue("Hello") . "<br>";
echo processValue(null) . "<br>";
?>
Value: 42 Value: Hello No value provided
Nullable Types Syntax
type1|type2|null
Union Type Restrictions
Union types have several important restrictions −
-
Duplicate types are not allowed − Declarations like
int|intorint|?intwill cause syntax errors -
void type cannot be combined −
voidcannot be part of a union type - Compile-time validation − Redundant types are checked during compilation
False Type in Union Types
PHP 8 introduced the false type as part of union types. This is commonly used for functions that return false on failure instead of null −
<?php
function findStudent(int $id): array|false
{
$students = [
1 => ["name" => "John", "grade" => "A"],
2 => ["name" => "Jane", "grade" => "B"]
];
return $students[$id] ?? false;
}
$result1 = findStudent(1);
$result2 = findStudent(999);
var_export($result1);
echo "<br>";
var_export($result2);
?>
array ( 'name' => 'John', 'grade' => 'A', ) false
False Type Rules
- false cannot be used as a standalone type
- Nullable false types like
false|nullor?falseare not allowed - Can be used in parameters, properties, and return values
- No true literal type exists − use
boolinstead
Conclusion
Union types in PHP 8 provide flexible type declarations while maintaining type safety. They support multiple types using the | operator and include special handling for nullable and false types, making PHP code more expressive and robust.
