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 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|100Variadic 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.0match 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; // 1php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.