How to check instanceof parent class?
Asked Answered
E

3

7

In PHP there is two classes: class parentTroll {...} and class troll extends parentTroll {...}

And then there is an object $troll = new troll();

How to check $troll instanceof parentTroll? This line returns false now.

Evangelical answered 21/5, 2014 at 10:57 Comment(0)
H
18

Following example returns true:

class parentTroll {}
class troll extends parentTroll {}
$troll = new troll();

var_dump($troll instanceof parentTroll);

Output:

boolean true

You can also use ReflectionClass:

var_dump((new ReflectionClass($troll))->getParentClass()->getName() == 'parentTroll');
Hoelscher answered 21/5, 2014 at 11:0 Comment(0)
I
2

The documentation disagrees

See http://www.php.net/manual/en/language.operators.type.php

And so does my testing of your code.

Inbeing answered 21/5, 2014 at 11:1 Comment(2)
Could you explain how it disagrees. It looks like it works with parent classes in Example #2: "Using instanceof with inherited classes"Analysand
"This line returns false now" is what I was disagreeing with. It actually returns true (as the accepted answer also says).Inbeing
P
0

There is metho is_subclass_of. Just use is_subclass_of($troll, Parent::class)

Pathway answered 4/6, 2022 at 4:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.