How to check the type of an object in PHP
Been working on something where you need to check the type of PHP objects? Doing that is pretty straightforward. In fact, there are two ways to do it, I'll show you both.
When you want to test an object for a particular type
You know there are predefined object types in PHP, you just call the
is_* functions to test. The following code shows you how to do the
is_null($var)- true if
is_object($var)- true if
$varis an object
is_string($var)- true if
$varis a string
is_numeric($var)- true if
$varis a numeric string
is_int($var)- true if
$varis an integer
is_float($var)- true if
$varis floating point number
is_bool($var)- true if
$varis a boolean
is_array($var)- true if $var is an array
is_resource($var)- true if
$varis a resource (mysql, file etc). Use
get_resource_typeto get the specific type.
is_scalar($var)- true if
$varis a scalar (primitive data types: int, float, string, boolean)
is_callable($var)- true if
$varis a function or works like a function
So what's the difference between
is_numericwill validate true even for quoted numbers (technically strings), eg: '31337', along with true numbers, eg: 31337. All non-binary form data come as strings - even numbers. In
$_GET[id]is a string! To check if the value of id is actually a number, you would need to use
truefor 31337, but not for '31337'. The scope of using
is_intis only within the PHP file, because all other numbers from external sources are passed to PHP as strings.
There are other
is_* functions like
When you want to get the type of the object
Sometimes, you don't want to test if the object is of any particular type - you just want to know its type - whatever it might be. Doing that is pretty easy -
gettype on an object will return these possible values:
- "double" (for historical reasons "double" is returned in case of a float, and not simply "float")
- "unknown type"
There is a downside to using
gettype: the return value may change in the future - according to the official PHP documentation. What it means is that your code might work fine for now, but once you upgrade PHP or your web host does it for you, your code is likely to stop working. No guarantee. Isn't that scary?