1.2.1329. Use Contravariance

Contravariance is compatible argument typehint. A child class may accept an object of a parent class of the argument type of its parent’s method.

Since a children class may accept a parent class of the argument type, the evolution is in opposite order.

Contravariance is a PHP 7.4 feature. Contravariance is distinct from return type covariance.

<?php
class X {
  function m(Y $z): X {}
}

// m is overwriting the parent's method.
// The return type is different.
// The return type is compatible, as Y is also a sub-class of X.
class Y extends X {
  function m(X $z): Y {}
}

?>

See also Covariant Returns and Contravariant Parameters and No title for `Php/UseCovariance <No anchor for Php/UseCovariance>`.

1.2.1329.1. Connex PHP features

1.2.1329.1.1. Specs

Short name

Php/UseContravariance

Rulesets

All, Appinfo, CE, Changed Behavior

Exakat since

1.9.3

PHP Version

With PHP 7.4 and more recent

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Available in

Entreprise Edition, Community Edition, Exakat Cloud