PHP8的一些语法新特性

PHP技术
374
0
0
2022-04-14
标签   PHP8

命名参数

function test($name, $age='18', $sex='男') {
    echo $name . '-------' . $age . '--------'. $sex;
}
test('Landy', age: 20, sex: '女'); //Landy-------20--------女  

还可以跳过参数

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

参数的顺序可以不固定了

test(age: 30, sex: '女', name: 'tom'); //tom-------30--------女   
<?php
class Person {
    public static function test($name, $age) {
       echo $name.'|'.$age;
    }
}
Person::test(age:100, name:'Landy'); //Landy|100  

还可以这样

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

test1(1,2, name:'Landy', age:11, sex:2);

Array
(
    [name] => Landy
    [age] => 11[sex] => 2
)

向下不兼容,PHP8.0后的函数都可以使用命名参数

match表达式

$a = 8.0;

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

可以和表达式匹配

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 => '没有匹配值'
};  //匹配函数

match为强类型匹配,还有一点需要注意的是之前match(){} 花括号后要写;,switch是不用的

构造函数里可直接定义属性

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