2
1

【PHP】nullの扱い方

Posted at

nullに対する四則演算や型変換を実行すると0に変換されてしまうケースがあり、条件分岐などが想定通りにならない場合がある。
その場合にどうすればよいか、もしくはnullをどのように扱えばうまくいったかを書いていく。

nullどうしの加算、減算、乗算

$plus     = null + null;
$minus    = null - null;
$multiply = null * null;
// nullにはならず、全て数値型の0に変換される
int(0)
int(0)
int(0)

nullどうしの除算

$division = null / null;
// エラーが発生
PHP Fatal error:  Uncaught DivisionByZeroError: Division by zero in XXX
Stack trace:
#0 {main}
  thrown in XXX

nullと数値の四則演算

$plusOne     = null + 1;
$minusOne    = null - 1;
$multiplyOne = null * 1;
$divisionOne = null / 1;
// nullが0のように扱われている
int(1)
int(-1)
int(0)
int(0)

nullの型変換

$castToInt    = (int) null;
$castToString = (string) null;
// エラーやnullにはならず、0に変換される
int(0)
string(0)

nullを考慮しておらず、変数や条件分岐が期待しない結果になった、もしくはエラーが発生してしまった場合にどうすればよいか

対策1

nullが存在するパターンを考慮し、条件分岐する

if (is_null($var)) {
    // $varがnullの場合の処理。早期リターンやエラー出力処理など
}

対策2

例外を投げる

If (is_null($var)) {
    throw new Exception(nullだよ)
}

対策3

nullを避けられないなら、関係者間でnullの扱い方を決めておく
例:nullの場合には特定の数値に変換して処理を続行する、エラーを出力する、など

参考

2
1
0

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
2
1