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) { /* ... */ }
}PHPDoc のアノテーションの代わりに、PHP ネイティブの文法で構造化されたメタデータを扱えるようになりました。
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,
) {}
}ボイラープレートのコードを減らすため、コンストラクタでプロパティを定義し、初期化します。
class Number {
/** @var int|float */
private $number;
/**
* @param float|int $number
*/
public function __construct($number) {
$this->number = $number;
}
}
new Number('NaN'); // Okclass Number {
public function __construct(
private int|float $number
) {}
}
new Number('NaN'); // TypeErrorPHPDoc のアノテーションを使って型を組み合わせる代わりに、実行時に検証が行われる union型 をネイティブで使えるようになりました。
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 expectedmatch は switch 文に似ていますが、以下の機能があります:
match は式なので、結果を返したり、変数に保存したりできます。match の分岐は一行の式だけをサポートしており、break 文は不要です。match は、型と値について、厳密な比較を行います。$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;null チェックの条件を追加する代わりに、nullsafe演算子 を使って呼び出しをチェインさせられるようになりました。呼び出しチェインのひとつが失敗すると、チェインの実行全体が停止し、null と評価されます。
0 == 'foobar' // true0 == 'foobar' // false数値形式の文字列と比較する場合は、PHP 8 は数値として比較を行います。それ以外の場合は、数値を文字列に変換し、文字列として比較を行います。
strlen([]); // Warning: strlen() expects parameter 1 to be string, array given
array_chunk([], -1); // Warning: array_chunk(): Size parameter expected to be greater than 0strlen([]); // 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ほとんどの内部関数は、引数の検証に失敗すると Error 例外をスローするようになりました。
PHP 8 は JITコンパイル のエンジンをふたつ搭載しています。トレーシングJITは、もっとも有望なふたつの人工的なベンチマークで、約3倍のパフォーマンスを示しました。また、長期間動いている特定のあるアプリケーションでは、1.5-2倍のパフォーマンス向上が見られました。典型的なアプリケーションのパフォーマンスは、PHP 7.4 と同等でした。
@ 演算子は、致命的なエラーを隠さなくなりました。mixed 型のサポート RFC
static 型をサポート RFC