⊗ppOpIhOI 36 of 107 menu

The instanceof Operator and Inheritance in OOP in PHP

Let's examine the features of inheritance when using the instanceof operator. Suppose we have a parent class and a child class:

<?php // Parent class: class ParentClass { } // Child class: class ChildClass extends ParentClass { } ?>

Let's create an object of the child class:

<?php $obj = new ChildClass; ?>

Now let's check using instanceof, whether our object belongs to the ParentClass class and the ChildClass class:

<?php var_dump($obj instanceof ChildClass); // will output true var_dump($obj instanceof ParentClass); // will also output true ?>

As you can see from the example - the instanceof operator does not distinguish between parent and child classes during the check.

Don't be confused - if the object is indeed of the parent class, then, of course, the check for belonging to the child class will return false:

<?php $obj = new ParentClass; // object of the parent class var_dump($obj instanceof ParentClass); // will output true var_dump($obj instanceof ChildClass); // will output false ?>

Make a User class with public properties name and surname.

Make an Employee class that will inherit from the User class and add a salary property.

Make a City class with public properties name and population.

Create 3 objects of the User class, 3 objects of the Employee class, 3 objects of the City class, and in an arbitrary order write them into the array $arr.

Loop through the $arr array and output a column of name properties to the screen for those objects that belong to the User class or a descendant of this class.

Loop through the $arr array and output a column of name properties to the screen for those objects that do not belong to the User class or a descendant of this class.

Loop through the $arr array and output a column of name properties to the screen for those objects that belong precisely to the User class, meaning not the City class and not the Employee class.

byenru