Be careful comparing ReflectionParameter::getType() and gettype() as they will not return the same results for a given type.
string - string // OK
int - integer // Type mismatch
bool - boolean // Type mismatch
array - array // OK
(PHP 4, PHP 5, PHP 7, PHP 8)
gettype — 変数の型を取得する
value
型を調べたい変数。
返された文字列は、以下のいずれかの値を持ちます。
"boolean"
"integer"
"double"
(歴史的な理由により
float の場合は、"float"
ではなく、
"double"
が返されます)
"string"
"array"
"object"
"resource"
"resource (closed)"
(PHP 7.2.0 以降)
"NULL"
"unknown type"
バージョン | 説明 |
---|---|
7.2.0 |
クローズ済みのリソースを渡すと 'resource (closed)' を返すようになりました。
以前は 'unknown type' を返していました。
|
例1 gettype() の例
<?php
$data = array(1, 1., NULL, new stdClass, 'foo');
foreach ($data as $value) {
echo gettype($value), "\n";
}
?>
上の例の出力は、 たとえば以下のようになります。
integer double NULL object string
Be careful comparing ReflectionParameter::getType() and gettype() as they will not return the same results for a given type.
string - string // OK
int - integer // Type mismatch
bool - boolean // Type mismatch
array - array // OK
Since ReflectionParameter::getType() and gettype() do not return the same type name, you can leverage the strpos() function.
use DateTime;
use ReflectionClass;
$myVar = 45;
# get the type of your variable
$varType = gettype($myVar);
$cls = new ReflectionClass(DateTime::class);
$mth = $cls->getMethod('setDate');
$params = $mth->getParameters();
foreach($params as $param) {
$paramTypes = $param instanceof ReflectionUnionType
? $param->getTypes()
: [$param];
foreach($paramTypes as $paramType) {
if (strpos($paramType, $varType) >= 0) {
echo "Parameter '". $paramType->getName() ."' has type '". $paramType->getType() ."' which matches the variable's type of '$varType'.\n";
}
}
}