PHP check for instance of DateTime?

2020-06-30 03:58发布

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.

4条回答
SAY GOODBYE
2楼-- · 2020-06-30 04:32

if ($var instanceof DateTime)

查看更多
Deceive 欺骗
3楼-- · 2020-06-30 04:36

What about instanceof

查看更多
一夜七次
4楼-- · 2020-06-30 04:38

You can use get_class function like this:

<?php

    $a = new DateTime();
    if (get_class($a) == 'DateTime') {
        echo "Datetime";
    }
查看更多
Melony?
5楼-- · 2020-06-30 04:51

You could try instanceof­Docs...

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

See also is_a­Docs:

if (is_a($var, 'DateTime')) {
  // true
}
查看更多
登录 后发表回答