首頁 > 後端開發 > PHP8 > 主體

聊聊PHP8的一些語法新特性

藏色散人
發布: 2023-02-17 11:54:01
轉載
3395 人瀏覽過

這篇文章向大家介紹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--------女
登入後複製
登入後複製
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中文網其他相關文章!

相關標籤:
來源:learnku.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!