Understanding PHP 8 Expanded Variance Support
Understand the expanded variance support in PHP 8 including covariant returns and contravariant parameters. Learn how these features conform to the Liskov Substitution Principle, enhance method signature flexibility, and help manage OOP backward-compatibility challenges to write more robust and maintainable PHP code.
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 ...