Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 767
Niklas R Avatar asked Mar 05 '12 15:03

Niklas R


3 Answers

You could try instanceof­Docs...

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

See also is_a­Docs:

if (is_a($var, 'DateTime')) {
  // true
}
like image 63
fire Avatar answered Nov 11 '22 00:11

fire


if ($var instanceof DateTime)

like image 10
Distdev Avatar answered Nov 10 '22 22:11

Distdev


You can use get_class function like this:

<?php

    $a = new DateTime();
    if (get_class($a) == 'DateTime') {
        echo "Datetime";
    }
like image 7
botzko Avatar answered Nov 11 '22 00:11

botzko