Union Types
PHP 8 allows specifying multiple possible types for function arguments, return types, and class properties using union types. This is achieved by separating the types with a vertical bar (|).
Syntax:
function foo(int|string $value): void {
// Function implementation
}
Example: This example shows the union type.
// Function accepting an integer or string
function printValue(int|string $value): void {
echo $value;
}
// Usage
printValue(10); // Output: 10
printValue("Hello"); // Output: Hello
Output:
10
Hello
What is New in PHP Type Hinting Support in PHP 8?
PHP 8 introduced several enhancements and new features related to type hinting. That will check the code for their respective type so that we can use our code efficiently.
These are the following features used in PHP Type Hitting Support:
Table of Content
- Union Types
- Mixed Type
- Static Return Type
- Inheritance of Contravariant Parameters
- Inheritance of Private Methods with Parameter Contravariance