Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP instanceof - return TRUE only for children

Tags:

php

I have two classes, A and B. B extends class A.

If I execute instance of A on an instance of B, it returns TRUE.

How can this be avoided?

like image 486
tzortzik Avatar asked Apr 30 '26 22:04

tzortzik


1 Answers

This is how instanceof works, and correctly so: if B inherits from A, it is also of type A.

However, you can check the precise class by using get_class() instead:

if (get_class($b_instance) == 'A') {
    // Not true
}
like image 172
ljacqu Avatar answered May 03 '26 10:05

ljacqu