Home >Backend Development >PHP8 >Let's talk about some new grammatical features of PHP8
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.'|'.$age; } }
Person::test(age:100, name:'Landy'); //Landy|100
It can also be like this
function test1($arg1,$arg2, ...$args) { print_r($args); } test1(1,2, name:'Landy', 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 => '匹配8.0', '8.0' => 'test 8.0', default => '没有匹配值' }; //匹配8.0
can match the expression
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 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!