PHP 8.0 是PHP語言的一次主版本更新。它包含很多新特性及優化,包括具名參數、聯合類型、注解、構造函數屬性提升、match表達式、空指針安全運算符、JIT,以及類型系統、錯誤處理和一致性方面的改進。
Just-In-Time compilation
PHP 8 引入了兩套JIT編譯引擎:
- Tracing JIT(在二者中最有前途)
- Function JIT
具名參數
- 調用函數/方法時,僅需指定必要的參數,跳過無需賦值的參數;
- 具名參數的寫法不受參數定義順序約束,因為有自解釋作用;
htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
htmlspecialchars($string, double_encode: false);
注解(Attributes)
替代了PHPDoc注解的寫法,成為PHP原生語法。
class PostsController
{
/**
* @Route("/api/posts/{id}", methods={"GET"})
*/
public function get($id) { /* ... */ }
}
class PostsController
{
#[Route("/api/posts/{id}", methods: ["GET"])]
public function get($id) { /* ... */ }
}
構造函數屬性提升
定義和初始化類屬性時,減少大量樣板代碼。
class Point {
public float $x;
public float $y;
public float $z;
public function __construct(
float $x = 0.0,
float $y = 0.0,
float $z = 0.0
) {
$this->x = $x;
$this->y = $y;
$this->z = $z;
}
}
class Point {
public function __construct(
public float $x = 0.0,
public float $y = 0.0,
public float $z = 0.0,
) {}
}
聯合類型
替代了PHPDoc注解的寫法,現在可以原生語法聲明聯合類型,且會在運行時執行相應驗證。
class Number {
/** @var int|float */
private $number;
/**
* @param float|int $number
*/
public function __construct($number) {
$this->number = $number;
}
}
new Number('NaN'); // Ok
class Number {
public function __construct(
private int|float $number
) {}
}
new Number('NaN'); // TypeError
Match 表達式
match 與 switch 類似,相比有如下特點:
- match 是表達式,即它的執行結果可被存儲到變量中或作為返回值
- match 的分支語句僅支持單行語句、且無需break;
- match 執行類型嚴格比較
switch (8.0) {
case '8.0':
$result = "Oh no!";
break;
case 8.0:
$result = "This is what I expected";
break;
}
echo $result;
//> Oh no!
echo match (8.0) {
'8.0' => "Oh no!",
8.0 => "This is what I expected",
};
//> This is what I expected
空指針安全運算符
使用新的空指針安全運算符,可以使用鏈式調用了,不再需要用以前的null條件判斷。在鏈式寫法中的某一級元素為null時,整個鏈式執行終止並返回null。
$country = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$country = $address->country;
}
}
}
$country = $session?->user?->getAddress()?->country;
更理性的字符串與數值比較
當一個數值與另一個字符串格式的數值進行比較時,PHP 8 采用數值比較;否則,將該數值轉換為字符串進行字符串比較。
0 == 'foobar' // true
0 == 'foobar' // false
內部函數類型一致性錯誤
更多的內部函數其參數驗證失敗時會拋出Error異常。
strlen([]); // Warning: strlen() expects parameter 1 to be string, array given
array_chunk([], -1); // Warning: array_chunk(): Size parameter expected to be greater than 0
strlen([]); // TypeError: strlen(): Argument #1 ($str) must be of type string, array given
array_chunk([], -1); // ValueError: array_chunk(): Argument #2 ($length) must be greater than 0
類型系統及錯誤處理機制改進
- 針對算術與位操作更嚴格的類型檢測;
- 抽象trait方法驗證
- ...
其它語法變化與改進
- ...
新的類、接口及函數
- Weak Map 類
- Stringable 接口
- str_contains(), str_starts_with(), str_ends_with()
- fdiv()
- get_debug_type()
- get_resource_id()
- token_get_all() 對象實現
- 新 DOM Traversal 及 Manipulation APIs