BentCoder
BentCoder

Reputation: 12740

Check if variable which stores name of a class is an instanceof a class

I might have missed something in is_a() and instanceof but is there a way to make this string version work?

$myclass = 'MyClass';

if ($myclass instanceof MyClass) {
    echo 'Yes';
} else {
    echo 'No';
}

This works fine as expected and prints Yes:

$myclass = new MyClass();

if ($myclass instanceof MyClass) {
    echo 'Yes';
 else {
    echo 'No';
}

Upvotes: 0

Views: 45

Answers (1)

Forien
Forien

Reputation: 2763

Question:
Check if variable which stores name of a class is an instanceof a class

My answer:

If a variable stores a name of a class it cannot be instance of that class because it's a string!

What you might wanted:

Check if variable stores a name of existing class

Solution to that:

if (class_exists($myclass)) { ... }

Upvotes: 3

Related Questions