はじめに

PHP における単一の式はそれぞれ、 その値に応じて、以下の組み込み型のうちのひとつを持ちます:

PHP は、動的に型付けを行う言語です。 これは、PHP が実行時に型を決定するため、 デフォルトでは変数の型を指定する必要がないということです。 しかし、 型宣言 を使うことで、 その一部に静的に型を指定することができます。

型は、それに対して行える操作を制限します。 しかし、式や変数に対して、型がサポートしていない操作を行うと、 PHP はその操作をサポートする 型に変換 しようとします。 この処理は、値が使われる文脈によって異なります。 詳細は 型の相互変換 のページを参照ください。

ヒント

型の比較表 も役に立つかもしれません。 さまざまな型の値の比較に関する例があります。

注意: ある式を強制的に他の型として評価させたい場合、 型キャスト を使います。 settype() 関数を変数に対して使うと、 変数の型をその場で変換できます。

の型と値を知りたい場合は、 var_dump() 関数を使用してください。 の型を知りたい場合は、 get_debug_type() を使用してください。 式がある型であるかどうかをチェックするには is_type 関数を代わりに使用してください。

例1 異なる型

<?php
$a_bool
= true; // bool
$a_str = "foo"; // string
$a_str2 = 'foo'; // string
$an_int = 12; // int

echo get_debug_type($a_bool), "\n";
echo
get_debug_type($a_str), "\n";

// 数値であれば、4を足す
if (is_int($an_int)) {
$an_int += 4;
}
var_dump($an_int);

// $a_bool が文字列であれば, それをprintする
if (is_string($a_bool)) {
echo
"String: $a_bool";
}
?>

上の例の PHP 8 での出力は、このようになります。:

bool
string
int(16)

注意: PHP 8.0.0 より前のバージョンでは、 get_debug_type() が使えません。 代わりに gettype() が使えますが、 この関数は正規化された型の名前を使いません。

add a note

User Contributed Notes 1 note

up
0
nitroacad at gmail dot com
13 days ago
Warning: A non-numeric value encountered in C:\Users\USER\Desktop\learnphp\hello.php on line 61
52The variable is a boolean.
The variable is a string.
The variable is a string.
The variable is an integer.
The variable is a float.

 <?php
        $a_bool = true;
        $a_str = "Hello, World!";
        $a_str2 = 'PHP is great!';
        $a_number = 42;
        $a_float = 3.14;

        if (is_int($a_number)) {
           echo $a_number += 10 . "<br>"; // this line gives us the warning you see above. the solution is to echo the break:
// down like so:
     // echo "<br>";
        } else {
            echo "The variable is not an integer.<br>";
        }

        if (get_debug_type($a_bool) == "bool") {
            echo "The variable is a boolean.<br>";
        } else {
            echo "The variable is not a boolean.<br>";
        }
        if (get_debug_type($a_str) == "string") {
            echo "The variable is a string.<br>";
        } else {
            echo "The variable is not a string.<br>";
        }
        if (get_debug_type($a_str2) == "string") {
            echo "The variable is a string.<br>";
        } else {
            echo "The variable is not a string.<br>";
        }
        if (get_debug_type($a_number) == "int") {
            echo "The variable is an integer.<br>";
        } else {
            echo "The variable is not an integer.<br>";
        }
        if (get_debug_type($a_float) == "float") {
            echo "The variable is a float.<br>";
        } else {
            echo "The variable is not a float.<br>";
        }
     ?>
To Top