gettype

(PHP 4, PHP 5, PHP 7, PHP 8)

gettype获取变量的类型

说明

gettype(mixed $value): string

返回 PHP value 变量的类型。 对于类型检查,请使用 is_* 函数。

参数

value

要检查类型的变量。

返回值

返回字符串,可能值为:

  • "boolean"
  • "integer"
  • "double" (由于历史原因,如果是浮点型,则返回 "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

参见

add a note

User Contributed Notes 3 notes

up
9
mohammad dot alavi1990 at gmail dot com
11 months ago
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
up
0
brainsmith dot maleficent+php at gmail dot com
1 day ago
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";
        }
    }
}
up
-57
Anonymous
2 years ago
Same as for "boolean" below, happens with integers. gettype() return "integer" yet proper type hint is "int".

If your project is PHP8+ then you should consider using get_debug_type() instead which seems to return proper types that match used for type hints.
To Top