現在の言語: 日本語

戻る

int型
php型宣言

phpで使用する型宣言のint型について
厳密な宣言で判定するために下記のようにphpの最初に宣言します。

[サンプル]

copy
class test1
{
  function judgeInt(int $num)
  {
    return $num;
  }
}
$cls1 = new test1();
$cls1->judgeInt("123");
$cls1->judgeInt(1.23);

//下記は上記クラスとは別テストと仮定します
$value = 1;
$value = null; // 警告なし、値は内部的に 0 として扱われる
echo "value:".(int)$value." <br>";
copy
class test1
{
	function judgeInt(int $num)
	{
		return $num;
	}
}
$cls1 = new test1();
$cls1->judgeInt("123");
$cls1->judgeInt(1.23);

//Assume the following is a separate test from the above class.
$value = 1;
$value = null; // No warning, the value is internally treated as 0.
echo "value:".(int)$value." <br>";

$cls1->judgeInt("123");
Fatal error: Uncaught TypeError: test1::judgeInt(): Argument #1 ($num) must be of type int, string given
PHP 7.0以降、厳密な型宣言(declare(strict_types=1);)を使用している場合
期待される型と異なる型の値が渡されるとTypeErrorが発生します。

$cls1->judgeInt(1.23);
PHP 8以降では、floatからintへの暗黙的な変換で精度が失われる場合に警告が発生します。
[警告例]
Deprecated: Implicit conversion from float 1.23 to int loses precision
phpのint型の範囲
環境サイズ(ビット)最大値(PHP_INT_MAX)
32bit322,147,483,647 (約 21億)
64bit649,223,372,036,854,775,807 (約 900京)
環境サイズ(ビット)最小値(PHP_INT_MIN)
64bit64-9,223,372,036,854,775,808 (約 -900京)

int型をオーバーフローすると自動的にfloatにキャストされます。
エラーは発生しませんが下位の桁が丸められてしまい
正確な値が保持できなくなります。
echo "value:".(int)$value."<br>";
[結果]
value:(int)
$valueがnullと判定します。
nullを文字列変換すると空文字になります。
そのため$valueが空文字となり上記の結果となります。

echo "value:".$value."<br>";
[結果]
value:
$valueはnullなので空白に変換されます。


copy
class test2
{
  private function judgeInt(int $num)
  {
    echo "judgeInt関数を実行しました。<br>";
  }
  function test()
  {
    try {
        $this->judgeInt(1.23); // TypeError が発生します
    } catch (TypeError $e) {
        // ここでエラーを捕捉し、代替処理をします
        echo "Caught TypeError: " . $e->getMessage() . PHP_EOL;
        // 仕様的には良くないとしても、ここでデフォルト値を返すなどの回避策が可能です
        // 例: return round(1.23);
    } finally {
        echo "Finally block executed (always runs).\n";
    }
  }
}
$cls2 = new test2();
$cls2->test();
copy
class test2
{
	private function judgeInt(int $num)
	{
		echo "The judgeInt function was executed. <br>";
	}
	function test()
	{
		try {
			$this->judgeInt(1.23); // A TypeError occurs.
		} catch (TypeError $e) {
			// Catch the error here and handle it accordingly.
			echo "Caught TypeError: " . $e->getMessage() . PHP_EOL;
			// Even though this is not technically correct, a workaround is possible, such as returning a default value.
			// Example: return round(1.23);
		} finally {
		echo "Finally block executed (always runs).\n";
		}
	}
}
$cls2 = new test2();
$cls2->test();

$this->judgeInt(1.23);
Caught TypeError: test2::judgeInt(): Argument #1 ($num) must be of type int
declare(strict_types=1);が有効な環境でnullを代入しようとすると、
TypeErrorが発生し、プログラムの実行が停止します。


copy
class test3
{
  private function judgeInt(int $num) 
  {
      echo "judgeInt関数を実行しました。<br>";
  }
  function test()
  {
    try {
        $this->judgeInt(null); // Fatal error: Uncaught TypeError
    } catch (TypeError $e) {
        echo "エラーを捕捉しました: " . $e->getMessage();
    }
  }
}
$cls3 = new test3();
$cls3->test();
copy
class test3
{
	private function judgeInt(int $num)
	{
		echo "The judgeInt function was executed.<br>";
	}
	function test()
	{
		try {
			$this->judgeInt(null); // Fatal error: Uncaught TypeError
		} catch (TypeError $e) {
			echo "Error caught: " . $e->getMessage();
		}
	}
}
$cls3 = new test3();
$cls3->test();

$this->judgeInt(null);
test3::judgeInt(): Argument #1 ($value) must be of type int, null given,
declare(strict_types=1);が有効な環境でnullを代入しようとすると、
TypeErrorが発生し、プログラムの実行が停止します。


copy
class test4
{
  private function judgeIntNullable(?int $num):int
  {
    if ($num === null) {
        echo "値はnullです。デフォルト値の0を使用します。<br>";
        $num = 0;
    }
    return $num;
  }
  function test(?int $num)
  {
    $this->judgeIntNullable($num);
  }
  function judgeIntNull(int $num):int
  {
    if ($num === null) {
        echo "値はnullです。デフォルト値の0を使用します。<br>";
        $num = 0;
    }
    return $num;
  }
}
$cls4 = new test4();
echo $cls4->test(null);
echo $cls4->judgeIntNull(null);
copy
class test4
{
	private function judgeIntNullable(?int $num):int
	{
		if ($num === null) {
			echo "Value is null. Using default value 0. <br>";
			$num = 0;
		}
		return $num;
		}
		function test(?int $num)
		{
			$this->judgeIntNullable($num);
		}
		function judgeIntNull(int $num):int
		{
			if ($num === null) {
				echo "Value is null. Using default value 0. <br>";
			$num = 0;
		}
		return $num;
	}
}
$cls4 = new test4();
echo $cls4->test(null);
echo $cls4->judgeIntNull(null);

int型の引数にnullを渡したときにnull許容型にすることで
関数内部でnullに対する判定処理をすることができます。
[judgeIntNullableを実行した結果]
echo "値はnullです。デフォルト値の0を使用します。<br>";

function judgeIntNull(int $num):int
Fatal error: Uncaught TypeError: test4::judgeIntNull(): Argument #1 ($num) must be of type int, null given
null許容型にしていないためエラーが発生します。

文字列(int)でキャストした結果説明
"123"123全て数値なのでそのまま変換されます。
"123abc"123"123"までが数値として認識され、aで停止します。
"12.3"12小数点も数値の一部とみなされますが、(int)キャストなので小数点以下は切り捨てられます。
"abc123"0先頭が数値ではないため、結果は0になります。
"0"00に変換されます。
""0空文字列は0に変換されます。


copy
class test5
{
  function test($value)
  {
      if($value === 100)
      {
        echo "data is num.<br>";
      }
      else
      {
        echo "data is string.<br>";
      }
  }
}
$cls5 = new test5();
$cls5->test("100");
$cls5->test("100"+0);
copy
class test5
{ 
	function test($value) 
	{ 
		if($value === 100) 
		{ 
			echo "data is num.<br>"; 
		} 
		else 
		{ 
			echo "data is string.<br>"; 
		} 
	}
}
$cls5 = new test5();
$cls5->test("100");
$cls5->test("100"+0);

$cls5->test("100");
インスタンス化したクラスオブジェクトから文字列数字を判定します。
function test($value)
...
if($value === 100)
型が不一致と判定されます。
[結果]
data is string.
$cls5->test("100"+0);
型が一致と判定します。
文字列に 0 を足すなどの算術演算を行うと、PHPの型ジャグリングにより数値に変換されます。
[結果]
data is num.




戻る

著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームページおよびアプリ等を利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。