本篇文章向大家介绍PHP8的一些语法新特性,有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
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(
p
.........................................................