htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
htmlspecialchars($string, double_encode: false);
class PostsController
{
/**
* @Route("/api/posts/{id}", methods={"GET"})
*/
public function get($id) { /* ... */ }
}
class PostsController
{
#[Route("/api/posts/{id}", methods: ["GET"])]
public function get($id) { /* ... */ }
}
現在可以使用 PHP 原生語法來使用結構化中繼資料,而不是 PHPDoc 註釋。
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,
) {}
}
更少的樣板程式碼來定義和初始化屬性。
類別 Number {
/** @var int|float */
私有 $number;
/**
* @param float|int $number
*/
公開 function __construct($number) {
$this->number = $number;
}
}
new Number('NaN'); // 可以
類別 Number {
公開 function __construct(
私有 int|float $number
) {}
}
new Number('NaN'); // 型別錯誤
您可以使用在執行階段驗證的原生聯集類型宣告,而不是使用 PHPDoc 註釋來組合類型。
switch (8.0) {
case '8.0':
$result = "糟糕!";
break;
case 8.0:
$result = "這就是我預期的";
break;
}
echo $result;
//> 糟糕!
echo match (8.0) {
'8.0' => "糟糕!",
8.0 => "這就是我預期的",
};
//> 這就是我預期的
新的 match 類似於 switch,並具有以下特性
$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;
現在可以使用新的 nullsafe 運算子進行一連串的呼叫,而不必再進行 null 值檢查。當鏈中其中一個元素的評估失敗時,整個鏈的執行就會中止,且整個鏈的評估結果為 null。
0 == 'foobar' // true
0 == 'foobar' // false
當與數字字串比較時,PHP 8 會使用數字比較。否則,它會將數字轉換為字串,然後使用字串比較。
strlen([]); // 警告:strlen() 預期參數 1 為字串,給定陣列
array_chunk([], -1); // 警告:array_chunk():大小參數應大於 0
strlen([]); // TypeError:strlen():參數 #1 ($str) 必須是字串類型,給定陣列
array_chunk([], -1); // ValueError:array_chunk():參數 #2 ($length) 必須大於 0
現在,如果參數驗證失敗,大多數內建函式都會拋出錯誤例外。
PHP 8 引入了兩個 JIT 編譯引擎。其中最有潛力的 Tracing JIT 在合成基準測試中顯示出大約 3 倍的效能提升,在某些特定的長時間運行應用程式中則有 1.5 到 2 倍的效能提升。典型的應用程式效能與 PHP 7.4 相當。