PHP 检查 DateTime 的实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9568793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:08:36  来源:igfitidea点击:

PHP check for instance of DateTime?

phpclassinstanceinstanceofisinstance

提问by Niklas R

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.

对我来说似乎有点重。

回答by fire

You could try instanceof­Docs...

你可以试试instanceof文档...

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

See also is_a­Docs:

另请参阅is_a文档

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

回答by Distdev

if ($var instanceof DateTime)

if ($var instanceof DateTime)

回答by botzko

You can use get_class function like this:

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

<?php

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

回答by rkosegi

What about instanceof

关于什么的instanceof