首頁  >  文章  >  後端開發  >  聊聊PHP8的一些語法新特性

聊聊PHP8的一些語法新特性

藏色散人
藏色散人轉載
2021-05-21 10:40:163504瀏覽

這篇文章向大家介紹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.&#39;|&#39;.$age;
    }
}
Person::test(age:100, name:&#39;Landy&#39;); //Landy|100

還可以這樣

function test1($arg1,$arg2, ...$args) {
    print_r($args);
}
test1(1,2, name:&#39;Landy&#39;, age:11, sex:2);
Array
(
    [name] => Landy
    [age] => 11
    [sex] => 2
)

向下不相容,PHP8.0 後的函數都可以使用命名參數

match 表達式

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

可以和表達式匹配

function test3() {
    return 8.0;
}
$a = 8.0;
echo match($a) {
    test3() => &#39;匹配函数&#39;,
    8.0 => &#39;匹配8.0&#39;,
    &#39;8.0&#39; => &#39;test 8.0&#39;,
    9,10,11 => &#39;多次匹配&#39;, //多次匹配
    default => &#39;没有匹配值&#39;
};  //匹配函数

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中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除