in PHP

The difference between class and type

Whenever you instantiate an object in PHP, you automatically create an object with an implicit type. In fact, you can “type hint” on just about any object in PHP, whether it’s a concrete object, an interface or an abstract class. Yet in object oriented development, there is in fact a distinct difference between an object’s class and type.

The difference is subtle but important. An object class deals with specific implementation details of the object. An object’s type is about the interface that the object uses to communicate with other objects.

Confused? Let’s dig a little deeper.

When we are talking about an object type, we’re talking about how the object represents itself to other objects. The type informs an object how to communicate to and interface with other objects. This is why interfaces can be treated as types just like classes themselves. Types typically can’t be instantiated, as they don’t have any concrete implementation themselves; they are components that are used in constructing concrete objects.

When we’re talking about an object’s class, on the other hand, we’re talking about specific implementations of an object. The class cares about the implementation details, and implements those details. A class may implement a specific interface as well, which informs the type of object created. The class can be instantiated.

This is part of why it’s important to type hint on specific types, rather than specific class names. Even though PHP will syntactically allow for the type hinting of concrete classes, the purpose of type hinting is to enforce the interface, not the implementation of a particular object.

Frustrated with your company’s development practices?

You don't have to be!

No matter what the issues are, they can be fixed. You can begin to shed light on these issues with my handy checklist.

Plus, I'll help you with strategies to approach the issues at the organization level and "punch above your weight."

Powered by ConvertKit