instanceof

PHP Logo

PHP instanceof Operator Tips

26th January 2021 - 9 minutes read time

The instanceof operator in PHP is great at making sure you are looking at a type of object before acting on it. Whilst it's straightforward to use on its own, using it can lead to some undesirable side effects.

As a basic example, let's create a couple of interfaces and classes to show the instanceof operator in action. Rather than just have some test names I am using object names that you might find in a system. This consists of User and Order that might form part of a commerce system.

interface UserInterface {}
class User implements UserInterface {}

interface OrderInterface {}
class Order implements OrderInterface {}

If we instantiate the User object we can detect if the user is an instance of the class User like this.

Read the full article