Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Contravariance

Contravariance allows a parameter type to be less specific in a child method, than that of its parent.

This means that a parameter $trunk in the method trumpet of the child class Calf can be a parent of the type in the method trumpet of the parent class.

Less specific types can be: the same type AfricanElephpant, a parent class of the AfricanElephpant type, here Elephpant, an interface implemented by the type AfricanElephpant, a union type, such as AfricanElephpant|string. In particular, the type may become nullable.

It cannot be a totally different type, an intersection type, such as AfricanElephpant&A, a different class that implements the same interface as AfricanElephpant, or a different scalar type.

<?php

class Elephpant {}

class AfricanElephpant extends Elephpant {
    // This method accepts an object compatible with AfricanElephpant, but less specific
    function trumpet(AfricanElephpant $trunk) { }
}

class Calf extends AfricanElephpant {
    function trumpet(Elephpant $trunk) { }
}

?>

Documentation

See Also