Skip to content

Instantly share code, notes, and snippets.

@tiffany-taylor
Last active March 12, 2020 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiffany-taylor/b3bc12b0052daa1d48ad9fb7571018c4 to your computer and use it in GitHub Desktop.
Save tiffany-taylor/b3bc12b0052daa1d48ad9fb7571018c4 to your computer and use it in GitHub Desktop.

Covariance and Contravariance

In PHP 7.2.0, partial contravariance was introduced by removing type resetrictions on parameters in a child method. As of PHP 7.4.0, full covariance and contravariance support was added.

Covariance allows a child's method to return a more specific type than the return type of its parent's method. Whereas, contravariance allows a parameter type to be less specific ina child method, than that of its parent.

Covariance

To illustrate how covariance works, a simple abstract parent class, Animal is created. Animal will be extended by children classes, Cat, and Dog.

(example)

Note that there aren't any methods which return values in this example. A few factories will be added which return a new object of class type Animal, Cat, or Dog.

(example)

Contravariance

Continuing with the previous example with classes Animal, Cat, and Dog, a class called Food and AnimalFood will be included, and a method eat is added to the Animal abstract class.

(example)
(change nom noms to eats)

In order to see the behavior of contravariance, the eat method is overriden in the Dog class to allow any Food type object. The Cat class remains unchanged.

(example)

The next example will show the behavior of contravariance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment