Last active
August 29, 2015 14:10
-
-
Save Danack/fe0b4cfd3ea90bc54628 to your computer and use it in GitHub Desktop.
Contravariance for multiple interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Document {} | |
interface JSONDocument extends Document {} | |
interface XMLDocument extends Document {} | |
// If PHP had it we could use covariance on the params | |
// interface Printer { | |
// function printDocument(Document $document); | |
// } | |
interface JSONPrinter { | |
function printDocument(JSONDocument $jsonDocument); | |
} | |
interface XMLPrinter { | |
function printDocument(XMLDocument $xmlDocument); | |
} | |
class MultiplePrinter implements JSONPrinter, XMLPrinter { | |
// Param of this function has to be contravariant to | |
// support multiple interfaces. | |
function printDocument(Document $document) { | |
if ($document instanceof JSONDocument) { | |
//... | |
} | |
else if ($document instanceof XMLDocument) { | |
//... | |
} | |
else { | |
//Unsupported type | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment