Exploring PHP 8.0’s New Features: Union Types and Named Arguments Explained

PHP 8.0 introduces powerful new capabilities such as union return type declarations and named argument calls, allowing functions to accept multiple possible types and parameters to be passed by name, with detailed code examples demonstrating usage, type handling, and potential pitfalls.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Exploring PHP 8.0’s New Features: Union Types and Named Arguments Explained

Union Return Type Declarations

PHP 8.0 allows a function to declare a union of possible return types, enabling parameters and return values to be either int or float. The example class Stu demonstrates methods add, sub, and mul using these unions.

<?php
class Stu {
    public function add(int|float $a, int|float $b): int {
        return $a + $b;
    }
    public function sub(int|float $a, int|float $b): float|int {
        return $a - $b;
    }
    public function mul(int|float $a, int|float $b, string $c): string {
        return $a + $b;
    }
}
$stu = new Stu();
$rest = $stu->add(10, 20);
var_dump($rest); // int(30)
$rest = $stu->sub(30.25, 20);
var_dump($rest); // float(10.25)
$rest = $stu->mul(30.25, 20, 'extra');
var_dump($rest); // string(5) "50.25"

Named Argument Calls

PHP 8.0 also supports named arguments, allowing callers to specify values by parameter name instead of position. This feature works with union types and variadic parameters, as shown in the following examples.

<?php
class Stu {
    public function add(int $a, int $b): int {
        return $a + $b;
    }
    public function sub(int|float $a, int|float $b, ...$c): float|int {
        // implementation omitted for brevity
    }
}
$stu = new Stu();
$rest = $stu->add(b: 120, a: 100);
var_dump($rest); // int(220)
$rest = $stu->sub(a: 10.3, b: 10);
var_dump($rest); // float(0.3000000000000007)

The article notes that when using named arguments, any subsequent arguments must also be named, otherwise a syntax error occurs.

These new features bring PHP closer to languages like Python, offering greater flexibility in type declarations and argument passing.

PHPUnion Typesnamed argumentsType Declarations
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.