Home > Backend Development > PHP8 > body text

Let's talk about some new grammatical features of PHP8

藏色散人
Release: 2023-02-17 11:54:01
forward
3531 people have browsed it

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--------女
Copy after login

You can alsoSkip parameters

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

The order of parameters does not need to be fixed

test(age: 30, sex: '女', name: 'tom'); //tom-------30--------女
Copy after login
<?php
class Person {
    public static function test($name, $age) {
        echo $name.&#39;|&#39;.$age;
    }
}
Copy after login
Person::test(age:100, name:&#39;Landy&#39;); //Landy|100
Copy after login

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
)
Copy after login

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
Copy after login

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;
};  //匹配函数
Copy after login

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
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!