PHP检查DateTime的实例?

时间:2022-08-25 17:05:11

Is this the only way to check if an object is an instance of a class, in my case of the DateTime class?

这是检查对象是否是类的实例的唯一方法,在我的DateTime类的情况下?

$cls = ReflectionClass("DateTime");
if (! $cls->isInstance( (object) $var ) ) {
    // is not an instance
}

It seems a bit heavy to me.

对我来说似乎有点沉重。

4 个解决方案

#1


115  

You could try instanceof­Docs...

你可以试试instanceofDocs ......

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

See also is_a­Docs:

另见is_aDocs:

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

#2


7  

if ($var instanceof DateTime)

if($ var instanceof DateTime)

#3


6  

You can use get_class function like this:

您可以像这样使用get_class函数:

<?php

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

#4


4  

What about instanceof

那个例子怎么样?

#1


115  

You could try instanceof­Docs...

你可以试试instanceofDocs ......

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

See also is_a­Docs:

另见is_aDocs:

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

#2


7  

if ($var instanceof DateTime)

if($ var instanceof DateTime)

#3


6  

You can use get_class function like this:

您可以像这样使用get_class函数:

<?php

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

#4


4  

What about instanceof

那个例子怎么样?