PHP check for instance of DateTime?
63,428
Solution 1
You could try instanceof
Docs...
if ($var instanceof DateTime) {
// true
}
See also is_a
Docs:
if (is_a($var, 'DateTime')) {
// true
}
Solution 2
if ($var instanceof DateTime)
Solution 3
You can use get_class function like this:
<?php
$a = new DateTime();
if (get_class($a) == 'DateTime') {
echo "Datetime";
}
Solution 4
What about instanceof
Author by
Niklas R
Updated on July 09, 2022Comments
-
Niklas R almost 2 years
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.
-
Niklas R about 12 yearsMan, I didn't find anything about that one with google .. :/ Thank you!
-
Chadwick Meyer almost 10 years@redolent If you are using Symfony or some other framework that uses namespaces, you may need to declare
use \DateTime
at the top of your file to make it look forDateTime
in the root namespace (not your app's namespace).