note 127860 added to language.oop5.variance

From: Date: Wed, 26 Oct 2022 00:48:24 +0000
Subject: note 127860 added to language.oop5.variance
Groups: php.notes 
Request: Send a blank email to php-notes+get-219812@lists.php.net to get a copy of this message
The gist of how the Liskov Substition Princple applies to class types is, basically: "If an object is an instance of something, it should be possible to use it wherever an instance of something is allowed". The Co- and Contravariance rules come from this expectation when you remember that "something" could be a parent class of the object. For the Cat/Animal example of the text, Cats are Animals, so it should be possible for Cats to go anywhere Animals can go. The variance rules formalise this. Covariance: A subclass can override a method in the parent class with one that has a narrower return type. (Return values can be more specific in more specific subclasses; they "vary in the same direction", hence "covariant"). If an object has a method you expect to produce Animals, you should be able to replace it with an object where that method produces only Cats. You'll only get Cats from it but Cats are Animals, which are what you expected from the object. Contravariance: A subclass can override a method in the parent class with one that has a parameter with a wider type. (Parameters can be less specific in more specific subclasses; they "vary in the opposite direction", hence "contravariant"). If an object has a method you expect to take Cats, you should be able to replace it with an object where that method takes any sort of Animal. You'll only be giving it Cats but Cats are Animals, which are what the object expected from you. So, if your code is working with an object of a certain class, and it's given an instance of a subclass to work with, it shouldn't cause any trouble: It might accept any sort of Animal where you're only giving it Cats, or it might only return Cats when you're happy to receive any sort of Animal, but LSP says "so what? Cats are Animals so you should both be satisfied." ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.159.161 (proxied: 125.238.199.71) ---- Manual Page -- https://php.net/manual/en/language.oop5.variance.php Edit -- https://main.php.net/note/edit/127860 Del: integrated -- https://main.php.net/note/delete/127860/integrated Del: useless -- https://main.php.net/note/delete/127860/useless Del: bad code -- https://main.php.net/note/delete/127860/bad+code Del: spam -- https://main.php.net/note/delete/127860/spam Del: non-english -- https://main.php.net/note/delete/127860/non-english Del: in docs -- https://main.php.net/note/delete/127860/in+docs Del: other reasons-- https://main.php.net/note/delete/127860 Reject -- https://main.php.net/note/reject/127860 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219812) next »