Php check type of object

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

gettypeGet the type of a variable

Description

gettype(mixed $value): string

Parameters

value

The variable being type checked.

Return Values

Possible values for the returned string are:

  • "boolean"
  • "integer"
  • "double" (for historical reasons "double" is returned in case of a float, and not simply "float")
  • "string"
  • "array"
  • "object"
  • "resource"
  • "resource (closed)" as of PHP 7.2.0
  • "NULL"
  • "unknown type"

Changelog

VersionDescription
7.2.0 Closed resources are now reported as 'resource (closed)'. Previously the returned value for closed resources were 'unknown type'.

Examples

Example #1 gettype() example

$data

= array(11.NULL, new stdClass'foo');

foreach (

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

The above example will output something similar to:

integer
double
NULL
object
string

See Also

  • get_debug_type() - Gets the type name of a variable in a way that is suitable for debugging
  • settype() - Set the type of a variable
  • get_class() - Returns the name of the class of an object
  • is_array() - Finds whether a variable is an array
  • is_bool() - Finds out whether a variable is a boolean
  • is_callable() - Verify that a value can be called as a function from the current scope.
  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_null() - Finds whether a variable is null
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_object() - Finds whether a variable is an object
  • is_resource() - Finds whether a variable is a resource
  • is_scalar() - Finds whether a variable is a scalar
  • is_string() - Find whether the type of a variable is string
  • function_exists() - Return true if the given function has been defined
  • method_exists() - Checks if the class method exists

Anonymous

8 months 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.

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

is_objectFinds whether a variable is an object

Description

is_object(mixed $value): bool

Parameters

value

The variable being evaluated.

Return Values

Returns true if value is an object, false otherwise.

Changelog

VersionDescription
7.2.0 is_object() now returns true for unserialized objects without a class definition (class of __PHP_Incomplete_Class). Previously false was returned.

Examples

Example #1 is_object() example

// Declare a simple function to return an 
// array from our object
function get_students($obj)
{
    if (!
is_object($obj)) {
        return 
false;
    }

    return

$obj->students;
}
// Declare a new class instance and fill up 
// some values
$obj = new stdClass();
$obj->students = array('Kalle''Ross''Felipe');var_dump(get_students(null));
var_dump(get_students($obj));
?>

See Also

  • is_bool() - Finds out whether a variable is a boolean
  • is_int() - Find whether the type of a variable is integer
  • is_float() - Finds whether the type of a variable is float
  • is_string() - Find whether the type of a variable is string
  • is_array() - Finds whether a variable is an array

mark at not4you dot com

11 years ago

Unserializes data as returned by the standard PHP serialize() function. If the unserialized object is not an array, it will be converted to one, particularily useful if it returns a __PHP_Incomplete_Class.

/**
*
* @param string $data Serialized data
*
* @return array    Unserialized array
*/
function unserialize2array($data) {
   
$obj = unserialize($data);
    if(
is_array($obj)) return $obj;
   
$arr = array();
    foreach(
$obj as $k=>$v) {
       
$arr[$k] = $v;
    }
    unset(
$arr['__PHP_Incomplete_Class_Name']);
    return
$arr;
}
?>

corychristison[aT-]lavacube(.dot)com

17 years ago

You can use is_object($this) to detect if the function is being called via instance or procedure.

Example:

class mrClass {

    function

test( )
    {
        if(
is_object($this) )
        {
        
// do something for instance method
           
echo 'this is an instance call
'
. "\n";
        }
        else
        {
        
// do something different for procedural method
           
echo 'this is a procedure call
'
. "\n";
        }
    }

}

$inst = new mrClass();
$inst->test();mrClass::test();?>

This would output:
this is an instance call

this is a procedure call

:-) Happy coding!

wadih at creationmw dot com

5 years ago

Note that closures return true when passed to is_object():

echo
   
is_object(
        function(){return
"hello";}
    );
?>

Returns true (1)

corychristison[aT-]lavacube(.dot)com

17 years ago

Thank you victor AT fourstones DOT net.

I have written a function to do what victor has suggested, with the ease of use of is_object. It can be used to replace is_object(), but has an extra field [$check], to compare to a certain name. If $check is left empty, it will just check if &$object is an object.

function is_obj( &$object, $check=null, $strict=true )
{
    if(
$check == null && is_object($object) )
    {
        return
true;
    }
    if(
is_object($object) )
    {
       
$object_name = get_class($object);
        if(
$strict === true )
        {
            if(
$object_name == $check )
            {
                return
true;
            }
        }
        else
        {
            if(
strtolower($object_name) == strtolower($check) )
            {
                return
true;
            }
        }
    }
}
?>

This could probably be cleaned up, but it's spaced out to be easy to read.

lbjay can be emailed at reallywow dot com

19 years ago

I'm not even sure how to articulate this, so I'm going to just include test code. Maybe someone else will someday wonder the same thing.

    error_reporting(E_ALL);
    class testParent
    {
        var $child;

        function testParent()
        {
            $this->child = new testChild();
        }
    }

    class testChild
    {
        function testChild()
        {
        }
    }

    $parent = new testParent();
    $parent2 = 'foobar';

    print join(',', Array(
        is_object($parent) ? 'yes' : 'no',
        is_object($parent->child) ? 'yes' : 'no',
        is_object($parent2) ? 'yes' : 'no',
        is_object($parent2->child) ? 'yes' : 'no'
    ));

?>

This prints "yes,yes,no,no". Basically this shows that you can use is_object to test if the child object is an object without worrying about an error if the parent object isn't an object either.

will

12 years ago

Just discovered:
is_a  (  object $object  ,  string $class_name  )
Which checks if the object is of this class or has this class as one of its parents

Which seems to do what a lot here are trying to replicate

victor AT fourstones DOT net

17 years ago

er, I don't think that's right, especially if calling from another object instance:

function test_this()
{
    $c2 = new C2();
    $c2->func();
    $c1 = new C1();
    $c1->func();
    C1::func();
}

class C2
{
    function func()
    {
        C1::func();
    }
}

class C1
{
    function func()
    {
        if( isset($this) )
        {
            if( strtolower(get_class($this)) != 'c1' )
                print("oops\n");
            else
                print("this is ok\n" );
        }
        else
        {
            print("static call\n");
        }
    }
}

test_this();
?>

yields:
---------- run-php ----------

oops
this is ok
static call

Senthryl

13 years ago

Cleaning it up even more:

function is_obj(&$object, $className = null, $caseSensitive = true) {
    return
is_object($object) && (!is_string($className) || preg_match('/^'.$className.'$/D'.($caseSensitive ? '' : 'i'), get_class($object)));
}
?>

shadow_games at abv dot bg

8 years ago

here i created one function that i wanted to find but i had never found :X

    function compare_two_object_recursive($object_1, $object_2, $object_1_Identifier = false, $object_2_Identifier = false){
        $object1 = (array)$object_1;
        $object2 = (array)$object_2;
        $object3 = array();

                $o1i = $object_1_Identifier ? $object_1_Identifier : 1;
        $o2i = $object_2_Identifier ? $object_2_Identifier : 2;

                foreach($object1 as $key => $value){
            if(is_object($object1[$key])){
                $object1[$key] = (array)$object1[$key];
                $object2[$key] = (array)$object2[$key];
                $object3[$key] = (object)compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }elseif(is_array($object1[$key])){
                $object3[$key] = compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }else{
                if($object1[$key] == $object2[$key]){
                    $object3[$key]['comparison_status'] = "SAME";
                }else{
                    $object3[$key]['comparison_status'] = "NOT THE SAME";
                    $object3[$key][$o1i] = $object1[$key];
                    $object3[$key][$o2i] = $object2[$key];
                }
            }
        }
        return $object3;
    }

gregdangelo at gmail dot com

14 years ago

cleaned up peter's code... use only one return statement

function is_obj( &$object, $check=null, $strict=true )
{
$result = false;
  if (is_object($object)) {
      if ($check == null) {
          $result =  true;
      } else {
           $object_name = get_class($object);
           $result =  ($strict === true)?
               ( $object_name == $check ):
               ( strtolower($object_name) == strtolower($check) );
      }  
  }
return $result;
}

How do you check if an object is an instance of a class PHP?

The instanceof keyword is used to check if an object belongs to a class. The comparison returns true if the object is an instance of the class, it returns false if it is not.

What is __ method __ in PHP?

"Method" is basically just the name for a function within a class (or class function). Therefore __METHOD__ consists of the class name and the function name called ( dog::name ), while __FUNCTION__ only gives you the name of the function without any reference to the class it might be in.

How do you check the datatype of a variable in PHP?

The gettype() function is an inbuilt function in PHP which is used to get the type of a variable. It is used to check the type of existing variable. Parameter: This function accepts a single parameter $var. It is the name of variable which is needed to be checked for type of variable.

How do you access the properties of an object in PHP?

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .