Skip to content

Instantly share code, notes, and snippets.

@Danack
Last active August 29, 2015 14:10
Show Gist options
  • Save Danack/fe0b4cfd3ea90bc54628 to your computer and use it in GitHub Desktop.
Save Danack/fe0b4cfd3ea90bc54628 to your computer and use it in GitHub Desktop.
Contravariance for multiple interface
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