PHP check for instance of DateTime?

PhpClassInstanceInstanceofIsinstance

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

You could try instanceof ­Docs...

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

See also is_a­Docs:

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

Solution 2 - Php

if ($var instanceof DateTime)

Solution 3 - Php

You can use get_class function like this:

<?php

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

Solution 4 - Php

What about instanceof

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNiklas RView Question on Stackoverflow
Solution 1 - PhpfireView Answer on Stackoverflow
Solution 2 - PhpDistdevView Answer on Stackoverflow
Solution 3 - PhpbotzkoView Answer on Stackoverflow
Solution 4 - PhprkosegiView Answer on Stackoverflow