PHP 7.4 计划在2019年11月21日发布,它主要新增了以下几个特性:
short closure
Improved type variance
serialization
__toString
php短闭包函数可以减少冗余代码:
array_map(function (User $user) {
return $user->id;
}, $users)array_map(fn(User $user) => $user->id, $users)需要注意几点:
use
$thisPHP 预加载可以极大的提高性能
优点:在 PHP 7.4 以前,如果你使用了框架来开发,每次请求文件就必须加载和重新编译。预加载在框架启动时在内存中加载文件,而且在后续请求中永久有效。
缺点:性能的提升会在其他方面花费很大的代价,每次预加载的文件发生改变时,框架需要重新启动。
class A
{
public string $name;
public Foo $foo;
}不得不说, PHP 越来越接近 Java 等强类型语言
Improved type variance协变返回类型:
class ParentType {}
class ChildType extends ParentType {}
class A
{
public function covariantReturnTypes(): ParentType
{ /* … */ }
}
class B extends A
{
public function covariantReturnTypes(): ChildType
{ /* … */ }
}依赖(是不是很熟悉):
class ParentType {}
class ChildType extends ParentType {}
class A
{
public function covariantReturnTypes(): ParentType
{ /* … */ }
}
class B extends A
{
public function covariantReturnTypes(): ChildType
{ /* … */ }
}在目前 > PHP 7 以后的写法:
$data['date'] = $data['date'] ?? new DateTime();在 PHP 7.4 你可以这样写:
$data['date'] ??= new DateTime();合并数组到另一个数组中,返回一维数组
$arrayA = [1, 2, 3];
$arrayB = [4, 5];
$result = [0, ...$arrayA, ...$arrayB, 6 ,7];
// [0, 1, 2, 3, 4, 5, 6, 7]注意:只对数字索引有效
RFC 添加了两个新的魔术方法 __serialize 和 __unserialize
允许使用下划线更直观的分隔数值
$unformattedNumber = 107925284.88;
$formattedNumber = 107_925_284.88;PHP 7.4 之前,如果你这样写:
echo "sum: " . $a + $b;PHP 会解析为:
echo ("sum: " . $a) + $b;PHP 8 将会解析为:
echo "sum :" . ($a + $b);__toString 中抛出异常PHP 7.4 将会新增 ReflectionReference 类
php 短标签<? 将会在 PHP 8 中移除, <?= 会继续保留
PHP 遗留了一些奇怪的怪癖,比如
1 ? 2 : 3 ? 4 : 5; // 将会在 PHP 7.4 中废弃,在 PHP 8中会抛出编译错误
(1 ? 2 : 3) ? 4 : 5; // 正确parent::var_dump 打印 DateTime 和 DateTimeImmutable shi'实例,将不再保留对象上的可访问属性openssl_random_pseudo_bytes 会在调用错误时抛出异常PDO 和 PDOStatement 实例将会生成一个 Exception 而不是 PDOException 异常get_object_vars() 打印 ArrayObject 实例将会返回 ArrayObject 自己的属性,而不是被包裹的数组或对象的值,数组强制转换不受影响
原文:https://segmentfault.com/a/1190000019554530