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 — Возвращает тип переменной
Возвращает тип PHP-переменной value
. Для проверки
типа переменной используйте функции is_*
.
value
Проверяемая переменная.
Возможными значениями возвращаемой строки являются:
"boolean"
"integer"
"double"
(по историческим причинам
в случае типа float возвращается "double"
, а не просто
"float"
)
"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";
}
}
}