Dennis
Dennis

Reputation: 8111

How can I test if a class instance belongs to one of the parent classes that are on the same level?

Say I have this:

class Bird{}
class PrettyBird extends Bird{}
class UglyBird extends Bird{}
class Duckling extends UglyBird{}

and I do this:

$bird = new Duckling();

OR

$bird = new UglyBird();

Suppose in my universe all I am interested in is if class belongs to UglyBird or PrettyBird. In case above, I want to test whether $bird belongs to UglyBird (super)class in both cases above.

How?

Currently I can do it by

if (get_class($bird) === UglyBird::class 
    or get_class($bird) === Duckling::class)
    print "MATCH!";

but that's impractical. For example, what if I create a new class that extends UglyBird. I will have to add that class into the if statement.

Upvotes: 0

Views: 38

Answers (3)

Dekel
Dekel

Reputation: 62676

You can use the get_parent_class function:

class Bird{}
class PrettyBird extends Bird{}
class UglyBird extends Bird{}
class Duckling extends UglyBird{}

$bird = new Duckling();
var_dump(get_parent_class($bird));
$bird = new UglyBird();
var_dump(get_parent_class($bird));

Output:

string(8) "UglyBird"
string(4) "Bird"

You can check:

if (get_parent_class(new Duckling()) == get_parent_class(new UglyBird())) {
    ....
}

Upvotes: 0

krlv
krlv

Reputation: 2380

You can use instanceof operator for this check:

if ($bird instanceof UglyBird) {
    print "MATCH!";
}

It will work for instances of UglyBird and all inherited classes

Check documentation for details: http://php.net/manual/en/language.operators.type.php

Upvotes: 2

Chin Leung
Chin Leung

Reputation: 14941

You can use the function is_subclass_of:

$bird = new Duckling();
$bird2 = new PrettyBird();

var_dump(is_subclass_of($bird, 'UglyBird')); // True
var_dump(is_subclass_of($bird2, 'UglyBird')); // False

Suppose you have a child class of PrettyBird:

class PrettyDuckling extends PrettyBird{}

And you want to know if the child of PrettyBird is a subclass of UglyBird:

$bird3 = new PrettyDuckling();
var_dump(is_subclass_of($bird3, 'PrettyBird')); // True
var_dump(is_subclass_of($bird3, 'UglyBird')); // False

Note that this will work for the parent of the parent as well:

var_dump(is_subclass_of($bird, 'Bird')); // True
var_dump(is_subclass_of($bird2, 'Bird')); // True
var_dump(is_subclass_of($bird3, 'Bird')); // True

Upvotes: 0

Related Questions