1. 属性添加限定类型

<?php
class User {
public int $age;
public string $name
}
$user = new User();
$user->age = 10;
$user->name = "张三";
//error
$user->age = "zhang";//需要传递int

2. 箭头函数

<?php
$factor = 10;
$nums = array_map(fn($n)=>$n * $factor,[1,2,3]);//[10,20,30]
//之前的写法
$nums = array_map(function($num)use($factor){
return $num * $factor;
},[1,2,3])

3.有限返回类型协变与参数类型逆变

<?php
class A {}
class B extends A {}

class Producer {

public function method(): A {}

}
class ChildProducer extends Producer {

public function method(): B {}

}

4. 数组解包

<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];//['banana', 'orange', 'apple', 'pear', 'watermelon'];
//老的写法
$fruits = array_merge[['banana', 'orange'],$parts,['watermelon']];

5. 空合并运算符赋值

<?php
$array['key'] ??= computeDefault();
// 老的写法
if (!isset($array['key'])) {

$array['key'] = computeDefault();

}
?>

6. 数值文字分隔符

<?php
6.674_083e-11; // float
299_792_458; // decimal
0xCAFE_F00D; // hexadecimal
0b0101_1111; // binary
?>

7. 允许从 __toString () 抛出异常

现在允许从 __toString() 引发异常,以往这会导致致命错误,字符串转换中现有的可恢复致命错误已转换为 Error 异常。

8. Filter

<?php
filter_var(1.00,FILTER_VALIDATE_FLOAT);
### 9. strip_tags 支持数组
<?php
strip_tags($str,['p','a','div']);
//老的写法
strip_tags($str,"<p><div>");


凤舞九天
48 声望5 粉丝