PHP check for instance of DateTime?

Niklas R picture Niklas R · Mar 5, 2012 · Viewed 56.9k times · Source

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.

Answer

fire picture fire · Mar 5, 2012

You could try instanceof­Docs...

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

See also is_a­Docs:

if (is_a($var, 'DateTime')) {
  // true
}