Niklas R
Niklas R

Reputation: 16890

PHP check for instance of DateTime?

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.

Upvotes: 54

Views: 69725

Answers (4)

fire
fire

Reputation: 21531

You could try instanceof­Docs...

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

See also is_a­Docs:

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

Upvotes: 161

botzko
botzko

Reputation: 630

You can use get_class function like this:

<?php

    $a = new DateTime();
    if (get_class($a) == 'DateTime') {
        echo "Datetime";
    }

Upvotes: 7

rkosegi
rkosegi

Reputation: 14678

What about instanceof

Upvotes: 5

Distdev
Distdev

Reputation: 2312

if ($var instanceof DateTime)

Upvotes: 10

Related Questions