Using Named Parameters and Match Expressions in PHP 8

This article explains PHP 8's named parameters, how they allow flexible argument ordering, skipping defaults, variadic usage, and demonstrates the new match expression with strict typing and constructor property promotion examples.

php Courses
php Courses
php Courses
Using Named Parameters and Match Expressions in PHP 8

PHP 8 introduces named parameters, enabling arguments to be passed by name rather than position, which allows skipping optional parameters and reordering them freely.

Example:

function test($name, $age='18', $sex='男') {
    echo $name . '-------' . $age . '--------' . $sex;
}

test('Landy', age: 20, sex: '女'); // Landy-------20--------女

You can also skip parameters and rely on defaults: test('Landy', sex: '女'); // Landy-------18--------女 The order of arguments is no longer fixed:

test(age: 30, sex: '女', name: 'tom'); // tom-------30--------女

Named parameters work with static methods as well:

class Person {
    public static function test($name, $age) {
        echo $name . '|' . $age;
    }
}

Person::test(age: 100, name: 'Landy'); // Landy|100

Variadic functions can receive named arguments after the fixed ones:

function test1($arg1, $arg2, ...$args) {
    print_r($args);
}

test1(1, 2, name: 'Landy', age: 11, sex: 2);
/*
Array
(
    [name] => Landy
    [age] => 11
    [sex] => 2
)
*/

The new match expression provides strict type matching:

$a = 8.0;
echo match($a) {
    8.0 => '匹配8.0',
    '8.0' => 'test 8.0',
    default => '没有匹配值',
}; // 匹配8.0
match

can also match expressions and multiple values, and requires a trailing semicolon:

function test3() {
    return 8.0;
}
$a = 8.0;
echo match($a) {
    test3() => '匹配函数',
    8.0 => '匹配8.0',
    '8.0' => 'test 8.0',
    9, 10, 11 => '多次匹配',
    default => '没有匹配值',
}; // 匹配函数

Constructor property promotion lets you define class properties directly in the constructor signature:

class Point {
    public function __construct(
        public float $x = 1.0,
        public float $y = 2.0,
        public float $z = 3.0,
    ) {}
}

echo (new Point())->x; // 1
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPnamed_parametersmatch expression
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

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.