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
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 3
echo (new Point())->x
还是
echo (new Point())->$x
2年前 评论
Lany (楼主) 2年前

参数名字换一个可能顺序就不行了

2年前 评论

在构造函数里设置并定义变量,太奇怪了。虽然省了不用重复写的流程。

2年前 评论
Lany (楼主) 2年前
pndx 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!