Understanding PHP 8 Expanded Variance Support

Learn about covariance and contravariance in PHP 8 and how they may help developers handle problems more effectively.

The concept of variance is at the heart of OOP. Variance is an umbrella term that covers how the various subtypes interrelate. Some 20 years ago, a pair of early computer scientists, Wing and Liskov, devised an important theorem that is at the heart of OOP subtypes, now known as the Liskov Substitution Principle.

Without going into the precise mathematics, this principle can be paraphrased as follows: “Class X can be considered a subtype of class Y if you are able to substitute an instance of X in place of an instance of Y, and the application’s behavior does not change in any way.”

Tip: The actual paper that first described and provided the precise mathematical formulaic definition of the Liskov Substitution Principle can be found here: Liskov, Barbara H., and Jeanette M. Wing. 1994. “A Behavioral Notion of Subtyping.ACM transactions on Programming Languages and Systems 16 (6): 1811–41.

We examine how PHP 8 provides enhanced variance support in the form of covariant returns and contravariant parameters. An understanding of covariance and contravariance will increase our ability to write good, solid code. Without this understanding, our code might produce inconsistent results and become the source of many bugs.

Let’s start by covering covariant returns.

Understanding covariant returns

Covariance support in PHP is designed to preserve the ordering of types from the most specific to the most general. A classic example of this is seen in how try / catch blocks are formulated:

  1. In the following example, a PDO instance is created inside the try block. The following two catch blocks look first for a PDOException. Following this is a second catch block that catches any class that implements Throwable. Because both the PHP Exception and Error classes implement Throwable, the second catch block ends up as a fallback for any error other than a PDOException:

Get hands-on with 1200+ tech skills courses.