PHP Velho Oeste 2024

はじめに

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

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

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

ヒント

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

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

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

<?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 add a note

User Contributed Notes 1 note

up
0
kuzawinski dot marcin_NOSPAM at gmail dot com
3 years ago
No, despite description here a `callable` still is not a a full-fledged primitive type in PHP.

<?php

function testFunc() { }

class
testClass {
   
    public function
__invole() { }
   
    public static function
testStaticMethod() { }
   
    public function
testMethod() { }
}

$o = new testClass();
$lambda = function() { };

$c1 = 'testFunc';
$c2 = ['testClass', 'testStaticMethod'];
$c3 = [$o, 'testMethod'];
$c4 = $lambda;
$c5 = $o;

var_dump(is_callable($c1));  // TRUE
var_dump(is_callable($c2));  // TRUE
var_dump(is_callable($c3));  // TRUE
var_dump(is_callable($c4));  // TRUE
var_dump(is_callable($c5));  // TRUE

var_dump(gettype($c1)); // string(6) "string"
var_dump(gettype($c2)); // string(5) "array"
var_dump(gettype($c3)); // string(5) "array"
var_dump(gettype($c4)); // string(6) "object"
var_dump(gettype($c5)); // string(6) "object"

?>
To Top