Home  >  Article  >  Backend Development  >  Let’s talk about some new grammatical features of PHP8

Let’s talk about some new grammatical features of PHP8

藏色散人
藏色散人forward
2021-05-21 10:40:163594browse

This article introduces some new grammatical features of PHP8 to you. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Some new syntax features of PHP8

Named parameters

function test($name, $age='18', $sex='男') {
    echo $name . '-------' . $age . '--------'. $sex;
}
test('Landy', age: 20, sex: '女'); //Landy-------20--------女

You can alsoSkip parameters

test('Landy', sex: '女'); //Landy-------18--------女

The order of parameters does not need to be fixed

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

It can also be like this

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
)

It is not backward compatible. Functions after PHP8.0 can use named parameters

match expression

$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

can match the expression

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 is a strong type match. Another thing to note is that before match (){} You should write after the curly braces; , switch is not used

Properties can be defined directly in the constructor

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

Recommended study: " PHP video tutorial

The above is the detailed content of Let’s talk about some new grammatical features of PHP8. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete