本篇文章向大家介绍php8的一些语法新特性,有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
PHP8的一些语法新特性
命名参数
function test($name, $age='18', $sex='男') {
echo $name . '-------' . $age . '--------'. $sex;
}
test('Landy', age: 20, sex: '女'); //Landy-------20--------女还可以跳过参数
test('Landy', sex: '女'); //Landy-------18--------女参数的顺序可以不固定了
立即学习“PHP免费学习笔记(深入)”;
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推荐学习:《PHP视频教程》
以上就是聊聊PHP8的一些语法新特性的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号