Understanding PHP 8 Expanded Variance Support
Learn about covariance and contravariance in PHP 8 and how they may help developers handle problems more effectively.
We'll cover the following
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:
In the following example, a
PDO
instance is created inside thetry
block. The following twocatch
blocks look first for aPDOException
. Following this is a secondcatch
block that catches any class that implementsThrowable
. Because both the PHPException
andError
classes implementThrowable
, the secondcatch
block ends up as a fallback for any error other than aPDOException
:
Get hands-on with 1200+ tech skills courses.