gettype

(PHP 3, PHP 4, PHP 5)

gettype -- 获取变量的类型

描述

string gettype ( mixed var )

返回 PHP 变量的类型 var.

警告

不要使用 gettype() 来测试某种类型,因为其返回的字符串在未来的版本中可能需要改变。此外,由于包含了字符串的比较,它的运行也是较慢的。

使用 is_* 函数代替。

返回的字符串的可能值为:

  • boolean”(从 PHP 4 起)

  • integer

  • double”(由于历史原因,如果是 float 则返回“double”,而不是“float”)

  • string

  • array

  • object

  • resource”(从 PHP 4 起)

  • NULL”(从 PHP 4 起)

  • “user function”(只用于 PHP 3,现已停用)

  • “unknown type”

对于 PHP 4,你应该使用 function_exists()method_exists() 取代先前将 gettype() 作用于函数的用法。

参见 settype()is_array()is_bool()is_float()is_integer()is_null()is_numeric()is_object()is_resource()is_scalar()is_string()


add a note add a note User Contributed Notes
gilthansNOSPAM at gmail dot com
12-Sep-2005 04:18
NaN and #IND will return double or float on gettype, while some inexistent values, like division by zero, will return as a boolean FALSE. 0 by the 0th potency returns 1, even though it is mathematically indetermined.

<?php
$number
= 5/0;
$number2 = sqrt(-3);
$number3 = pow(0, 0);
$number4 = 0/0;

echo
$number."<br />";
echo
$number2."<br />";
echo
$number3."<br />";
echo
$number4."<br />";
echo
"<br />";
echo
gettype($number)."<br />";
echo
gettype($number2)."<br />";
echo
gettype($number3)."<br />";
echo
gettype($number4);
?>

This will return:

-1.#IND
1

boolean
double
integer
boolean

0
1
1
0
PHP Warning: Division by zero in C\test.php on line 2 PHP Warning: Division by zero in C:\test.php on line 5
matt at appstate
17-Dec-2004 03:10
Here is something that had me stumped with regards to gettype and is_object.
Gettype will report an incomplete object as such, whereas is_object will return FALSE.

if (!is_object($incomplete_obj)) {
   echo 'This variable is not an object, it is a/an ' . gettype($incomplete_obj);
}

Will print:
This variable is not an object, it is a/an object
jose at vocis dot com
15-Sep-2000 12:22
Also returns "NULL" for variables assigned the return of a function that returned no value via "return;".

<code>

function weird(){
   return;
}
$a=weird();

</code>

isset($a) <> 1
empty($a) <> 1
gettype($a) == NULL

-Jose Batista
ojones at dotclick dot com
01-Sep-2000 01:19
After calling OCIResult to retrieve a NULL result from an Oracle result-set, gettype returns the string 'NULL'.