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.

PHP
// 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

Similar Reads

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 (|)....

Mixed Type

PHP 8 introduces a new mixed type declaration. This type allows any type to be passed, similar to the dynamic typing in languages like JavaScript. It’s useful when you want to accept any type but still want to maintain type safety for other arguments....

Static Return Type

PHP 8 introduced the ability to specify the return type as static in a class method. This means that the return type will be the same as the class in which the method is defined, providing better support for fluent interfaces and method chaining....

Inheritance of Contravariant Parameters

In PHP 8, contravariant parameter types are now allowed when overriding methods in subclasses. This means that you can type hint a parameter in a child class method with a type that is a superclass of the type specified in the parent class method. This enhances the flexibility of method overriding while still maintaining type safety....

Inheritance of Private Methods with Parameter Contravariance

PHP 8 extends the support for contravariant parameters to private methods in subclasses. Previously, this was not allowed due to potential violations of type safety, but PHP 8 relaxes this restriction....