Web・開発

PHP 8.6: 新機能、非推奨関数、および実践的な移行ガイド

PHP 8.6: New Features, Deprecated Functions, and a Practical Migration Guide

PHP 8.6へのアップグレードは、非推奨のPHP関数、MySQLi、mbstring、CSV、セッションの前後例と実践的な移行チェックリストを含みます。

PHP 8.6.0は2026年11月19日にリリースされました。 headline機能は興味深いですが、実際のサイトを維持管理する開発者にとって、緊急の質問はしばしば異なります: 既存のコードのどの行がdeprecation noticeを出力し始め、どのように書き換えるべきか? このガイドはまずマイグレーションウォークを最優先します。各例は非推奨のAPIを特定し、置換えを示し、機械的な検索と置換えが危険な箇所を強調します。deprecation noticeは即座の致命的エラーではありません:コードの注意を要することを警告し、多くの場合、将来のメジャーバージョンでAPIが削除される前に知らせます。

PHP 8.6 migration path: inventory, staging, logs, fixes and regression tests

1. 本番前にランタイムを確認

アプリケーションが動作するのと同じPHP環境でこれらのコマンドを実行してください(CLIとウェブPHPは異なるバイナリと設定を使用する可能性があります):

php -v
php -m
php --ini

プロジェクトで使用されている拡張機能を確認し、特にmbstring、mysqliおよびintlを確認してください。フレームワーク、CMS、拡張機能およびホスト環境が明示的にPHP 8.6をサポートしていることを確認してください。サイトが起動するだけだからといって単に互換性があると推測しないでください。

ステージング環境では、診断メッセージをパブリックHTMLから外しつつすべてのエラーを記録します:

<?php
error_reporting(E_ALL);
ini_set('log_errors', '1');
ini_set('display_errors', '0');

これらのランタイム設定は制御されたテストには役立ちます。長時間実行される環境ではサーバーレベルでログの設定を優先してください。エラーログが書き込み可能でプライベートであることを確認してください。ページがまだレンダリングされても、Deprecatedメッセージは実用的です。

2. すぐに確認:非推奨のAPIと代わりに使うもの

Deprecated in PHP 8.6 推奨されるアプローチ マイグレーションキャビアト
is_integer(), is_long() is_int() Direct aliases
is_double() is_float() Direct alias
doubleval() floatval() Direct alias
spl_object_hash() spl_object_id() Return type changes from string to int
mb_ereg(), mb_eregi() preg_match() Adapt pattern syntax and Unicode flags
mb_ereg_replace() preg_replace() Check escaping, replacement semantics and errors
mysqli_stmt_init() mysqli_prepare() Prepare immediately
mysqli_get_charset() mysqli_character_set_name() Only if the charset name is needed
SplFileObject::fgetcsv() fgetcsv() on a stream Revisit stream position and CSV settings
SplFileObject::fputcsv() fputcsv() on a stream Pass delimiter, enclosure and escape explicitly
strcoll() Collator::compare() Requires intl; choose a locale
SORT_LOCALE_STRING Collator::sort() / asort() Locale behavior can change
spl_classes() ReflectionExtension::getClassNames() Inspect the appropriate extension
Third argument of define() Omit the argument The old case-insensitive mode is gone
return in finally Return outside finally Avoid suppressing exceptions
Object passed to array_walk() get_object_vars() first By-reference edits may no longer mutate the object
metaphone() A maintained phonetic implementation No drop-in core replacement

Some APIs have no exact replacement. The correct migration may require changing the design rather than renaming a function. See the official PHP 8.6 deprecations list.

3. Simple aliases: safe, fast fixes

Before — deprecated:

<?php
if (is_integer($quantity) && is_double($price)) {
    $total = doubleval($price) * $quantity;
}

After:

<?php
if (is_int($quantity) && is_float($price)) {
    $total = floatval($price) * $quantity;
}

The aliases have the same semantics. Do not assume that is_float(40) is true: an integer remains an integer. That behavior was already present before the migration.

For a string amount, floatval() is a conversion, not a money-safe decimal representation. Keep the project's existing money-handling strategy rather than changing it as part of an unrelated PHP upgrade.

4. Migrating mbstring regular expressions

The mb_ereg* family is deprecated because its underlying Oniguruma regex engine is no longer maintained. PHP recommends PCRE for many use cases, but the pattern dialects are not identical.

Before:

<?php
$isReference = mb_ereg('^[0-9]+$', $reference) !== false;

After (ASCII digits only):

<?php
$isReference = preg_match('/^[0-9]+$/D', $reference) === 1;

Here the D modifier makes $ match only at the end of the subject. For Unicode text, use an appropriate UTF-8 pattern and the u modifier:

<?php
$isName = preg_match('/^\p{L}+(?:[ -]\p{L}+)*$/uD', $name) === 1;

Before — replacement:

<?php
$clean = mb_ereg_replace('[[:space:]]+', ' ', $text);
Illustration of the article's main concept

After — replacement:

<?php
$clean = preg_replace('/\s+/u', ' ', $text);
if ($clean === null) {
    throw new RuntimeException('Regular expression failed');
}

The two patterns may differ on some Unicode whitespace. For real migrations, test accented characters, newlines, invalid UTF-8, capture groups and backreferences against actual project data. Do not mass-replace every mb_ereg call without reviewing the expression.

5. MySQLi: prepare a statement in one step

Before — deprecated:

<?php
$stmt = mysqli_stmt_init($mysqli);
mysqli_stmt_prepare($stmt, 'SELECT name FROM users WHERE id = ?');
mysqli_stmt_bind_param($stmt, 'i', $userId);
mysqli_stmt_execute($stmt);

After:

<?php
$stmt = mysqli_prepare($mysqli, 'SELECT name FROM users WHERE id = ?');
mysqli_stmt_bind_param($stmt, 'i', $userId);
mysqli_stmt_execute($stmt);

With the object-oriented API, use $mysqli->prepare($sql) instead of $mysqli->stmt_init() followed by prepare(). Keep your existing error handling and close statements appropriately.

The separate mysqli_get_charset() API is also deprecated. If you only need the current charset name:

<?php
$charsetName = mysqli_character_set_name($mysqli);

This is not a replacement for all fields of the old charset-information object. If the code depends on collation metadata, inspect what it actually needs and query the server appropriately.

6. CSV: replace deprecated SplFileObject CSV methods

The CSV-specific methods on SplFileObject are deprecated. For new and migrated code, use the stream-based fgetcsv() and fputcsv() functions.

Before:

<?php
$file = new SplFileObject($path, 'r');
while (!$file->eof()) {
    $row = $file->fgetcsv();
    // Process row
}

After:

<?php
$handle = fopen($path, 'rb');
if ($handle === false) {
    throw new RuntimeException('Cannot open CSV file');
}
try {
    while (($row = fgetcsv($handle, 0, ',', '"', '')) !== false) {
        // Process row
    }
} finally {
    fclose($handle);
}

The empty escape argument disables PHP's proprietary escape mechanism; test this choice against the format your source system exports. Check blank lines, headers, delimiters, embedded newlines and encoding. This example illustrates the API change, not a universal CSV parser.

For writing, use fputcsv($handle, $fields, ',', '"', ''). Preserve the original file's expected dialect.

7. Object identity: spl_object_hash() is not a content hash

Before:

<?php
$key = spl_object_hash($object);

After:

<?php
$key = spl_object_id($object);

The replacement returns an integer, not a string. If keys are serialized, stored in a database or exposed through an API, review consumers first. Neither function produces a persistent identifier across requests, and IDs can be reused after objects are destroyed. For a map keyed by live object identity, consider SplObjectStorage or WeakMap, depending on lifetime requirements.

8. A return in finally can hide failures

Before — deprecated and misleading:

<?php
function loadSettings(): array
{
    try {
        return readSettings();
    } finally {
        return []; // Overrides the result and hides exceptions
    }
}

After — preserve cleanup without overriding the result:

Technical workflow illustration
<?php
function loadSettings(): array
{
    try {
        return readSettings();
    } finally {
        releaseTemporaryResources();
    }
}

If the original code intentionally returned a fallback, move that decision into a catch block with explicit handling. Do not silently swallow an exception that should reach the caller.

9. Locale-sensitive sorting and other less obvious changes

strcoll() and the SORT_LOCALE_STRING sorting flag are deprecated. The recommended intl alternative is Collator:

<?php
$collator = new Collator('fr_FR');
$names = ['Émile', 'Alice', 'Zoé'];
$collator->sort($names);

Check that intl is installed. Locale-aware sorting is a business rule: test your expected order rather than assuming ICU and a process-global locale will always behave identically.

Other migration items deserve explicit attention:

  • ArrayIterator: sorting, flags and serialization methods such as asort(), ksort(), setFlags() and serialize() are deprecated. Sort the underlying array or use ArrayObject when its API is appropriate; do not assume an iterator and a container are interchangeable.
  • Custom session handlers: implement both create_sid() and validateId() as required by the updated interfaces/behavior. PHP 8.6 enables stricter session defaults; test login, session rotation and persistence.
  • __debugInfo(): use a non-nullable array return type; returning null was already deprecated.
  • define(): remove the third case_insensitive argument, even when it is false.
  • http_build_query() and array_walk(): passing objects where arrays are expected is deprecated. Convert intentionally using get_object_vars() or construct the desired array explicitly.
  • metaphone(): no equivalent built-in PHP replacement exists. Choose and test a maintained, language-appropriate phonetic algorithm.
  • Reserved identifiers: names such as let, is, readonly (function) and namespace (class constant) have new deprecation restrictions. Rename affected declarations carefully.
  • Reflection: review invalid objects passed to ReflectionProperty::setValue() and object arguments supplied when invoking static methods.

Consult the full migration guide for edge cases not covered in this practical selection.

10. Find deprecated calls in an existing project

Start with a read-only inventory. On Linux or macOS:

grep -RnE --include='*.php' \
  'is_integer\(|is_long\(|is_double\(|doubleval\(|spl_object_hash\(|mb_ereg\(|mb_ereg_replace\(|mysqli_stmt_init\(|mysqli_get_charset\(' \
  ./src

Replace ./src with the actual directory. This text search may match comments or strings, and will miss dynamic calls, namespaced aliases and other deprecated APIs. It is a starting point, not a complete static analyzer.

For a cross-platform option, an editor's Find in Files can search for the same names. Do not edit vendor or CMS core files directly: update the upstream package or submit a patch to its maintainer.

A safe PHP 8.6 migration workflow with staging, log review and regression testing

A reproducible migration sequence

  1. Record the current PHP version and enabled extensions.
  2. Back up files and database; prepare a staging copy.
  3. Run the project under PHP 8.6 with deprecation logging enabled.
  4. Inventory warnings by file and line, then group by API.
  5. Fix first-party code with targeted changes; update third-party dependencies separately.
  6. Rerun unit/integration tests and important user journeys.
  7. Check forms, login, sessions, email, payments, scheduled jobs, CSV import/export and database access.
  8. Deploy with a rollback plan; monitor error logs after release.

Joomla and WordPress: PHP 8.6 being released does not mean every CMS version, extension or plugin supports it. Confirm compatibility with the exact versions in use and test a staging environment first. Do not use the upgrade as a reason to patch core or vendor code directly.

11. What is actually new in PHP 8.6?

Beyond deprecations, the release adds several language and runtime features:

Feature Practical use
Partial function application Pre-fill arguments and obtain a callable for the remaining ones
clamp() Constrain a value between a minimum and maximum
\Time\Duration Represent elapsed time rather than a calendar date
SortDirection Express ascending/descending direction through a standard enum
Io\Poll Support stream polling in event-loop and I/O libraries
Defaults for readonly properties Simplify selected immutable class declarations

A small, immediately useful example is clamp():

<?php
// Before PHP 8.6
$percentage = min(100, max(0, $input));

// PHP 8.6
$percentage = clamp($input, 0, 100);

The code is easier to read, but the migration priority should still be compatibility testing. The other features are not necessary just to keep an existing application working. See the official release announcement.

12. Before you switch the production PHP version

Treat PHP 8.6 as a controlled upgrade, not a button to click on a busy production server. A sensible release checklist is: supported CMS and dependencies; available extensions; no unexpected deprecation flood; tests passing; verified database and session behavior; tested backups; and a rollback procedure.

Bottom line: PHP 8.6 brings useful features, but its deprecations are often where maintenance work begins. Fix the straightforward aliases first, then test behavioral migrations—especially regex, CSV, sessions and locale-sensitive operations—against real data.

Official sources