PHP 8系の新機能まとめ|7系からの移行ポイント

プログラミング言語

PHP 8系は、性能・型安全性・記法すべてが大きく進化しました。PHP 7系で書かれた既存コードを移行するうえで知っておきたい新機能を、本記事でまとめて解説します。

JITコンパイラ

PHP 8.0からJITが導入され、CPU集約的な処理で大幅な性能向上が得られます。Webアプリではフレームワーク次第ですが、CLIスクリプトでは特に効果が出やすいです。

名前付き引数

function createUser(string $name, int $age = 18, bool $admin = false) {}

createUser(name: 'A', admin: true);  // ageは省略

コンストラクタプロモーション

class User {
    public function __construct(
        public string $name,
        public int $age = 0,
    ) {}
}
// プロパティ宣言が不要に

Enums(PHP 8.1+)

enum Status: string {
    case Draft = 'draft';
    case Published = 'published';
    case Archived = 'archived';
}

$s = Status::Published;
echo $s->value; // 'published'

readonlyプロパティ

class Point {
    public function __construct(
        public readonly float $x,
        public readonly float $y,
    ) {}
}
$p = new Point(1, 2);
// $p->x = 5; // エラー

Union / Intersection / never型

function format(int|string $v): string { ... }   // Union
function check(Countable&Stringable $v) { ... }   // Intersection
function fail(): never { throw new Exception(); } // never

match式

$label = match($status) {
    Status::Draft => '下書き',
    Status::Published => '公開',
    Status::Archived => 'アーカイブ',
};

nullsafe演算子

$country = $user?->getAddress()?->country;
// 途中がnullなら全体がnull

移行のポイント

  • 非推奨警告を見ながら段階的にPHP 8系へ
  • 厳格な型宣言(declare(strict_types=1))を活用
  • Composer 2系・PHPStan・Psalmで静的解析を強化
  • Laravel・Symfony・WordPressともPHP 8系を正式サポート

まとめ

PHP 8系は、現代的な言語機能と性能を兼ね備えた大きな進化です。Enums・readonly・match・nullsafe・JITを活用すれば、PHPコードがよりシンプル・安全・速くなります。既存7系プロジェクトは計画的に移行する価値が十分あります。