SOLID

PHP Logo

PHP instanceof Operator Tips

26th January 2021 - 8 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.

PHP Logo

Traits Versus Inheritance In PHP

9th February 2020 - 6 minutes read time

The other day I was conducting a code review and found that a developer had used a trait to give two classes the same group of utility methods. Whilst there was nothing wrong with this in terms of functionality, I asked the developer why they had chosen to use traits instead of inheritance. We eventually decided that an inheritance model would be better suited to the situation but I thought I would go through some of the thought processes here.

What Is A Trait?

A trait, if you weren't aware, is like a class, but you don't instantiate it directly. Traits are defined using the trait keyword and are otherwise quite like a class in structure.

The idea is that code is essentially copied into the class you want to use it in from the trait and the class acts like it had that code all along. For example, let's take a simple trait.

PHP Logo

SOLID Principles In PHP

20th August 2018 - 14 minutes read time
SOLID is a set of object oriented design principles aimed at making code more maintainable and flexible. They were coined by Robert "Uncle Bob" Martin in the year 2000 in his paper Design Principles and Design Patterns. The SOLID principles apply to any object oriented language, but I'm going to concentrate on what they mean in a PHP application in this post.