54

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.

1

4 Answers 4

161

You could try instanceof­Docs...

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

See also is_a­Docs:

if (is_a($var, 'DateTime')) {
  // true
}
Sign up to request clarification or add additional context in comments.

1 Comment

Man, I didn't find anything about that one with google .. :/ Thank you!
10

if ($var instanceof DateTime)

Comments

7

You can use get_class function like this:

<?php

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

1 Comment

@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 for DateTime in the root namespace (not your app's namespace).
5

What about instanceof

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.