搜尋
首頁後端開發PHP8聊聊PHP8的一些語法新特性

這篇文章向大家介紹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。如有侵權,請聯絡admin@php.cn刪除

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境