1. 程式人生 > 程式設計 >PHP 7.4.0 釋出

PHP 7.4.0 釋出

PHP 7.4.0 釋出了,此版本標誌著 PHP 7 系列的第四次特性更新。

PHP 7.4.0 進行了許多改進,並帶來了一些新特性,包括:

Typed Properties 型別屬性

類屬性現在支援型別宣告,以下示例將強制 $User-> id 只能分配 int 值,而 $User-> name 只能分配 string 值。

<?php
class User {
    public int $id;
    public string $name;
}
?>
複製程式碼

Arrow Functions 箭頭函式

箭頭函式提供了用於定義具有隱式按值作用域繫結的函式的簡寫語法。

<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor,[1,2,3,4]);
// $nums = array(10,20,30,40);
?>
複製程式碼

將閉包傳遞給 array_map 或 array_filter 等函式時,它可以發揮極大的作用。

// A collection of Post objects $posts = [/* … */];

$ids = array_map(fn($post) => $post->id,$posts);
複製程式碼

Limited Return Type Covariance and Argument Type Contravariance

 有限返回型別協變與引數型別逆變

僅當使用自動載入時,才提供完全協變/逆變支援。在單個檔案中,只能使用非迴圈型別引用,因為所有類在被引用之前都必須可用。

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

class Producer {
    public function method(): A {}
}
class ChildProducer extends Producer {
    public function method(): B {}
}
?>
複製程式碼

Unpacking Inside Arrays 打包內部陣列

<?php
$parts = ['apple','pear'];
$fruits = ['banana','orange',...$parts,'watermelon'];
// ['banana','apple','pear','watermelon'];
?>
複製程式碼

Numeric Literal Separator 數值文字分隔符

數字文字可以在數字之間包含下劃線。

<?php
6.674_083e-11; // float
299_792_458;   // decimal
0xCAFE_F00D;   // hexadecimal
0b0101_1111;   // binary
?>
複製程式碼

Weak References 弱引用

弱引用使程式設計師可以保留對物件的引用,不會阻止物件被銷燬。

Allow Exceptions from __toString() 允許從 __toString() 丟擲異常

現在允許從 __toString() 引發異常,以往這會導致致命錯誤,字串轉換中現有的可恢復致命錯誤已轉換為 Error 異常。

Opcache Preloading Opcache 預載入

新增 Opcache 預載入支援。

此外還有一些棄用,以及從核心中刪除一些擴充套件,詳情檢視: