PHP8 Union types

PHP 8 Nullsafe operator

Instead of PHPDoc annotations for a combination of types, you can use native union type declarations that are validated at runtime.




// PHP 7
class Number {
  /** @var int|float */
  private $number;

  /**
   * @param float|int $number
   */
  public function __construct($number) {
    $this->number = $number;
  }
}

new Number('NaN'); // Ok

// PHP 8
class Number {
  public function __construct(
    private int|float $number
  ) {}
}

new Number('NaN'); // TypeError

That’s it!. Please share your thoughts or suggestions in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *