3.

PHP Parse error: syntax error, unexpected 'class' の対処

編集
この記事の要点
  • PHP Parse error: syntax error, unexpected 'class' (T_CLASS)古い PHP バージョンで新しい構文を使ったとき発生
  • 原因 ①: PHP 5.4 以前で trait や class const 表現を使った
  • 原因 ②: ::class 構文(PHP 5.5+)を古い PHP で使った
  • 原因 ③: 名前空間 / use トレイトの記法エラー
  • 対処: PHP バージョン確認 + コードに合うバージョンへアップグレード

 

エラーの状況

PHP Parse error:  syntax error, unexpected 'class' (T_CLASS) in /path/to/file.php on line 10
PHP Parse error:  syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) ...

このエラーは PHP パーサが「ここで class キーワードは予期していない」と判断した時に発生します。多くは使用している PHP の機能がそのバージョンでは未対応の場合です。

主な原因と対処

原因 1: ::class 構文 (PHP 5.5+)

// PHP 5.5+ で導入された ::class
$className = User::class;       // → "App\Models\User"

class_alias(MyClass::class, "Alias");

// PHP 5.4 以前で実行するとエラー
// 対処: PHP 5.5+ にアップグレード
// または文字列リテラルで書く
$className = "App\\Models\\User";

原因 2: 配列の短縮構文 [] (PHP 5.4+)

// PHP 5.4+
$arr = ["a", "b", "c"];

// PHP 5.3 以前
$arr = array("a", "b", "c");  // ← こちらが必要

原因 3: トレイト (PHP 5.4+)

// PHP 5.4+
trait Loggable {
    public function log() { ... }
}

class User {
    use Loggable;
}

// PHP 5.3 以前は trait 自体が存在しない

原因 4: 名前空間 (PHP 5.3+)

// PHP 5.3+ のみ
namespace App\Models;

use App\Http\Controllers\Controller;

class User extends Controller { }

// PHP 5.2 以前は名前空間なし、_ 区切りで擬似化
class App_Models_User extends App_Http_Controllers_Controller { }

原因 5: 無名クラス (PHP 7.0+)

// PHP 7.0+
$obj = new class {
    public function hello() { return "Hi"; }
};

// PHP 5.x ではエラー

原因 6: タイプヒント / 戻り値型 (PHP 7.0+ / 7.1+ / 8.0+)

// PHP 7.0+
function add(int $a, int $b): int {
    return $a + $b;
}

// PHP 7.1+
function find(?int $id): ?User { ... }

// PHP 8.0+
function process(string|int $value): array|false { ... }

// PHP 7 未満ではこれらの構文でエラー

原因の特定

PHP バージョン確認

# CLI
$ php -v
PHP 7.4.33 (cli) (built: ...)
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies

# Web サーバ経由


# または info.php
$ echo " /var/www/info.php

エラー行の前後を確認

エラーメッセージの「line N」の前後 5 行を見て、新しい構文を使っていないかチェック:

# ファイルの該当行を表示
$ sed -n "5,15p" /path/to/file.php

対処方法

方法 1: PHP をアップグレード(推奨)

# Ubuntu/Debian
$ sudo apt update
$ sudo apt install php8.2

# CentOS/RHEL
$ sudo yum install epel-release
$ sudo yum install https://rpms.remirepo.net/enterprise/remi-release-8.rpm
$ sudo yum module enable php:remi-8.2
$ sudo yum install php

# macOS Homebrew
$ brew install php@8.2

# 確認
$ php -v

方法 2: コードを古い PHP 互換に書き換え

本番サーバの PHP を上げられない場合は、コードを書き換え:

// PHP 5.5+ の ::class を文字列に
// Before:
$className = User::class;
// After:
$className = "App\\Models\\User";

// [] 配列を array() に
// Before:
$arr = [1, 2, 3];
// After:
$arr = array(1, 2, 3);

// 型宣言を削除
// Before:
function add(int $a, int $b): int { return $a + $b; }
// After:
function add($a, $b) { return $a + $b; }

方法 3: composer の PHP 要件で互換性チェック

// composer.json
{
    "require": {
        "php": "^8.1"
    }
}

# 依存ライブラリが PHP 8.1+ を要求しているか確認
$ composer outdated --direct

類似エラー

エラー原因
unexpected \'class\' (T_CLASS)このページのケース
unexpected \'[\' (T_ARRAY)PHP 5.3 で短縮配列構文 []
unexpected \'use\' (T_USE)PHP 5.3 で use 構文(名前空間 / トレイト)
unexpected \'?\'PHP 7 未満で nullable / 三項演算子省略形
unexpected \'function\'アロー関数 (PHP 7.4+)

PHP バージョン別新機能まとめ

PHP新機能
5.3namespace, use, クロージャ
5.4trait, [] 短縮配列, callable 型
5.5::class, generator, finally
5.6可変引数 (...), 定数式
7.0型宣言, 戻り値型, 無名クラス, ??演算子
7.1nullable 型 (?), void 戻り値
7.4アロー関数 (fn), 型プロパティ, ??=
8.0match, ユニオン型, named arguments
8.1readonly, enum, never 型
8.2readonly class, 交差型
8.3typed class constants, json_validate

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost'
  2. Add [~] to fillable property to allow mass assignment on [App\~].
  3. PHP Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in ~
  4. Changing columns for table "~" requires Doctrine DBAL; install "doctrine/dbal"
  5. MethodNotAllowedHttpException No message
  6. Class 'Doctrine\DBAL\Driver\PDOMySql\Driver' not found
  7. production.ERROR: No application encryption key has been specified.
  8. Dotenv values containing spaces must be surrounded by quotes.
  9. Laravel \ Socialite \ Two \ InvalidStateException
  10. The page has expired due to inactivity. Please refresh and try again.
  11. Failed to clone https://github.com/symfony/thanks.git via https, ssh protocol
  12. Illegal offset type
  13. Cannot access protected property Illuminate\Http\Request::$...
  14. Emitted value instead of an instance of Error
  15. 画像保存時にInternal Server Error
  16. Failed to authenticate on SMTP server with username ...
  17. PostTooLargeException
  18. Database hosts array is empty.
  19. Invalid request (Unsupported SSL request)
  20. does not comply with psr-4 autoloading standard. Skipping.
  21. MySQLのSTR_TO_DATE関数を使用するとnullが返却される問題