2

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?

tzortzik
  • 4,993
  • 9
  • 57
  • 88

4 Answers4

5

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
}
ljacqu
  • 2,132
  • 1
  • 17
  • 21
1

You need to check class by get_class function

if( get_class($Binst) == 'A' ) {
}
Dmitry Bezik
  • 349
  • 1
  • 5
1

You may want to know the Class name of an object.

Try to use get_class($Object).

Example:

$objA = new A(); $objB = new B();

get_class($objA) will return "A".

and

get_class($objB) will return "B".

Then if you use

if (get_class($objB) == "A") { echo "Its a A"; }

Elias Soares
  • 9,884
  • 4
  • 29
  • 59
1

Use is_subclass_of() function: is_subclass_of($b, 'A')

Marek
  • 7,337
  • 1
  • 22
  • 33