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:

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

Let's create an object of the child class:

index.php<?php
  $obj = new ChildClass;
?>

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

index.php<?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<?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
?>
Задание 1

Make a User class with public properties name and surname.

Задание 2

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

Задание 3

Make a City class with public properties name and population.

Задание 4

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.

Задание 5

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.

Задание 6

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.

Задание 7

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.