53

Is this the only way to check if an object is an instance of a class, in my case of the DateTime class?

$cls = ReflectionClass("DateTime");
if (! $cls->isInstance( (object) $var ) ) {
    // is not an instance
}

It seems a bit heavy to me.

Niklas R
  • 16,299
  • 28
  • 108
  • 203
  • See as well: [How to know what class is an object instance of? (php5)](http://stackoverflow.com/questions/1928491/how-to-know-what-class-is-an-object-instance-of-php5) (Not really a duplicate) – hakre Mar 05 '12 at 15:48

4 Answers4

159

You could try instanceof­Docs...

if ($var instanceof DateTime) {
  // true
}

See also is_a­Docs:

if (is_a($var, 'DateTime')) {
  // true
}
Baby
  • 5,062
  • 3
  • 30
  • 52
fire
  • 21,383
  • 17
  • 79
  • 114
10

if ($var instanceof DateTime)

Distdev
  • 2,312
  • 16
  • 23
7

You can use get_class function like this:

<?php

    $a = new DateTime();
    if (get_class($a) == 'DateTime') {
        echo "Datetime";
    }
botzko
  • 630
  • 3
  • 8
  • 5
    @redolent If you are using Symfony or some other framework that uses namespaces, you may need to declare `use \DateTime` at the top of your file to make it look for `DateTime` in the root namespace (not your app's namespace). – Chadwick Meyer Jul 21 '14 at 21:50
5

What about instanceof

rkosegi
  • 14,165
  • 5
  • 50
  • 83