Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

21
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHP 7.xから8.xに移行する人は、暗黙的型変換に注意

Posted at

環境:PHP 8.0+ 生PHP(フレームワークなし)
PHP 7.xから8.xに移行されたシステムで機能開発中、以下のようなエラーに遭遇しました。今後も同様のケースがありそうなので、備忘録として残しておきます。

  1. 現象の再現コードとエラー内容
  • string + stringTypeError になる例
  • PHP 7.4と8.0以降での挙動の違い
$form['pc_num'] = '3';
$form['pc_num2'] = '4';
echo $form['pc_num'] + $form['pc_num2']; // PHP 7.4: 7 / PHP 8.0+: TypeError

2. なぜこのエラーが発生するのか?

  • PHP 8.0以降では型の扱いが厳密になり、文字列同士の + による暗黙的な数値変換が行われなくなった

3. 対処方法とその是非

intval() で型変換
可読性・安全性が高く、初心者にも扱いやすい

(int) キャストとの違い

(int) '4abc'     // => 4
intval('4abc')   // => 4

※ 実質ほぼ同じだが、ブログ読者によっては (int) の方が好まれるケースもあります。
バリデーションをした後に型変換をするのが無難なイメージでした。

filter_var() を使った堅牢な例

$val = filter_var($input, FILTER_VALIDATE_INT);
if ($val === false) {
    // 無効な数値
}

4. フォーム値を扱うときのベストプラクティス

  • クライアントバリデーションとサーバー側の型変換
  • Requestオブジェクトの利用(LaravelなどのFWでは特に)
  • 数値で来るとは限らない前提でロジックを書く姿勢

5. まとめ

  • PHP 8.0以降では暗黙の型変換に頼らないことが基本
  • フレームワークを使っていても、低レイヤーでエラーになるケースはある
  • 特に「昔から動いていたコードをメンテする現場」では要注意

6. 感想

まだまだ PHP 7.x を使用しているシステムは多くあります。バージョンアップを予定している方は、意図せず不具合が発生する可能性もあるので注意が必要です。
ここまで見てくださってありがとうございます!

21
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
c-limber-inc
福岡でWebシステムの受託開発を行っています。

Linked from these articles

Comments

tadsan
@tadsan(園島 ぬぬ)
(Edited)

現象の再現コードとエラー内容
string + string が TypeError になる例
PHP 7.4と8.0以降での挙動の違い

そんなことはないんじゃないでしょうか

以下のように変更すると実行時にWarningが発生しますが、TypeErrorではありません。

$form['pc_num'] = '3a';
$form['pc_num2'] = '4b';
echo $form['pc_num'] + $form['pc_num2'];
// PHP 8.x- Warning: A non-numeric value encountered in ...
// PHP 7.1-7.4 Notice: A non well formed numeric value encountered in ...
// PHP 7.0まではエラーなし


TypeErrorが発生するのは、PHP 8.0以降の以下のようなコードです。

<?php

echo add('3', '4'), PHP_EOL;
echo add('3a', '4b'), PHP_EOL;

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

0

Let's comment your feelings that are more than good

21
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address