Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Last active April 13, 2020 13:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcaskill/986b7af72b48849a3b5acf7cfeee5666 to your computer and use it in GitHub Desktop.
Save mcaskill/986b7af72b48849a3b5acf7cfeee5666 to your computer and use it in GitHub Desktop.
PHP : Get the type, resource name, or class name of a variable.

get_var_type

(PHP 5 >= 5.4)
get_var_type — Get the type, resource name, or class name of a variable.

Description

string get_var_type( mixed &$var )

Returns the type (name if an object or resource) of the PHP variable var.

Based on Pavel Lang's get_type() function.

Parameters

  • var — The variable being type checked.

Return Values

If the given var is:

  • a resource, this function will return the value from get_resource_type()
  • an object, this function will return the value from get_class()
  • else, this function will return the value from gettype()

Examples

Example #1 get_var_type() example

$data = array(1, 1., NULL, new ArrayIterator, 'foo', mysql_connect());

foreach ($data as $value) {
    echo gettype($value), "\n";
}

The above example will output something similar to:

integer
double
NULL
ArrayIterator
string
mysql link

Installation

With Composer

$ composer require mcaskill/php-get-var-type

Without Composer

Why are you not using composer? Download Function.Fallback.php from the gist and save the file into your project path somewhere.

{
"name": "mcaskill/php-get-var-type",
"description": "Get the type, resource name, or class name of a variable.",
"license": "MIT",
"authors": [
{
"name": "Chauncey McAskill",
"email": "chauncey@mcaskill.ca",
"homepage": "https://github.com/mcaskill"
}
],
"keywords": [
"function"
],
"extra": {
"branch-alias": {
"dev-master": "1.x-dev"
}
},
"require": {
"php": ">=5.4.0"
},
"autoload": {
"files": ["Function.Get-Var-Type.php"]
}
}
<?php
if (!function_exists('get_var_type')) {
/**
* Get the type, resource name, or class name of a variable.
*
* Returns the type (name if an object or resource) of the PHP variable $var.
*
* @link http://php.net/manual/en/function.gettype.php#104224
* @param mixed $var The variable being type checked.
* @return string
*/
function get_var_type($var)
{
if (is_object($var)) {
return get_class($var);
}
if (is_resource($var)) {
return get_resource_type($var);
}
return gettype($var);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment