PHP 7.4 新特性

栏目: PHP · 发布时间: 6年前

内容简介:短闭包函数可以减少冗余代码:需要注意几点:

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
$this

预加载

PHP 预加载可以极大的提高性能

优点:在 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; // 正确

不再向后兼容的变更

  1. 弃用在没有父类的情况下调用 parent::
  2. 调用 var_dump 打印 DateTimeDateTimeImmutable shi'实例,将不再保留对象上的可访问属性
  3. openssl_random_pseudo_bytes 会在调用错误时抛出异常
  4. 序列化 PDOPDOStatement 实例将会生成一个 Exception 而不是 PDOException 异常
  5. 调用 get_object_vars() 打印 ArrayObject 实例将会返回 ArrayObject 自己的属性,而不是被包裹的数组或对象的值,

数组强制转换不受影响


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Haskell

Haskell

Simon Thompson / Addison-Wesley / 1999-3-16 / GBP 40.99

The second edition of Haskell: The Craft of Functional Programming is essential reading for beginners to functional programming and newcomers to the Haskell programming language. The emphasis is on th......一起来看看 《Haskell》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

SHA 加密
SHA 加密

SHA 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换