1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<sect1 xml:id="language.oop5.variance" xmlns="http://docbook.org/ns/docbook">
<title>Covariance and Contravariance</title>
<para>
In PHP 7.2.0, partial contravariance was introduced by removing type restrictions
on parameters in a child method. As of PHP 7.4.0, full covariance and contravariance
support was added.
</para>
<para>
Covariance allows a child's method to return a more specific type than the return type
of its parent's method. Contravariance allows a parameter type to be less
specific in a child method, than that of its parent.
</para>
<para>
A type declaration is considered more specific in the following case:
<itemizedlist>
<listitem>
<simpara>
A type is removed from a
<link linkend="language.types.type-system.composite.union">union type</link>
</simpara>
</listitem>
<listitem>
<simpara>
A type is added to an
<link linkend="language.types.type-system.composite.intersection">intersection type</link>
</simpara>
</listitem>
<listitem>
<simpara>
A class type is changed to a child class type
</simpara>
</listitem>
<listitem>
<simpara>
<type>iterable</type> is changed to <type>array</type> or <classname>Traversable</classname>
</simpara>
</listitem>
</itemizedlist>
A type class is considered less specific if the opposite is true.
</para>
<sect2 xml:id="language.oop5.variance.covariance">
<title>Covariance</title>
<para>
To illustrate how covariance works, a simple abstract parent class, <varname>Animal</varname>
is created. <varname>Animal</varname> will be extended by children classes,
<varname>Cat</varname>, and <varname>Dog</varname>.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
abstract class Animal
{
protected string $name;
public function __construct(string $name)
{
$this->name = $name;
}
abstract public function speak();
}
class Dog extends Animal
{
public function speak()
{
echo $this->name . " barks";
}
}
class Cat extends Animal
{
public function speak()
{
echo $this->name . " meows";
}
}
]]>
</programlisting>
</informalexample>
<para>
Note that there aren't any methods which return values in this example. A few factories
will be added which return a new object of class type <varname>Animal</varname>,
<varname>Cat</varname>, or <varname>Dog</varname>.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
interface AnimalShelter
{
public function adopt(string $name): Animal;
}
class CatShelter implements AnimalShelter
{
public function adopt(string $name): Cat // instead of returning class type Animal, it can return class type Cat
{
return new Cat($name);
}
}
class DogShelter implements AnimalShelter
{
public function adopt(string $name): Dog // instead of returning class type Animal, it can return class type Dog
{
return new Dog($name);
}
}
$kitty = (new CatShelter)->adopt("Ricky");
$kitty->speak();
echo "\n";
$doggy = (new DogShelter)->adopt("Mavrick");
$doggy->speak();
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Ricky meows
Mavrick barks
]]>
</screen>
</informalexample>
</sect2>
<sect2 xml:id="language.oop5.variance.contravariance">
<title>Contravariance</title>
<para>
Continuing with the previous example with the classes <varname>Animal</varname>,
<varname>Cat</varname>, and <varname>Dog</varname>, a class called
<varname>Food</varname> and <varname>AnimalFood</varname> will be included, and
a method <varname>eat(AnimalFood $food)</varname> is added to the <varname>Animal</varname>
abstract class.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Food {}
class AnimalFood extends Food {}
abstract class Animal
{
protected string $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function eat(AnimalFood $food)
{
echo $this->name . " eats " . get_class($food);
}
}
]]>
</programlisting>
</informalexample>
<para>
In order to see the behavior of contravariance, the
<varname>eat</varname> method is overridden in the <varname>Dog</varname> class to allow
any <varname>Food</varname> type object. The <varname>Cat</varname> class remains unchanged.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Dog extends Animal
{
public function eat(Food $food) {
echo $this->name . " eats " . get_class($food);
}
}
]]>
</programlisting>
</informalexample>
<para>
The next example will show the behavior of contravariance.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$kitty = (new CatShelter)->adopt("Ricky");
$catFood = new AnimalFood();
$kitty->eat($catFood);
echo "\n";
$doggy = (new DogShelter)->adopt("Mavrick");
$banana = new Food();
$doggy->eat($banana);
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Ricky eats AnimalFood
Mavrick eats Food
]]>
</screen>
<para>
But what happens if <varname>$kitty</varname> tries to <methodname>eat</methodname> the
<varname>$banana</varname>?
</para>
<programlisting role="php">
<![CDATA[
$kitty->eat($banana);
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Fatal error: Uncaught TypeError: Argument 1 passed to Animal::eat() must be an instance of AnimalFood, instance of Food given
]]>
</screen>
</informalexample>
</sect2>
<sect2>
<title>Property variance</title>
<simpara>
By default, properties are neither covariant nor contravariant, hence invariant.
That is, their type may not change in a child class at all.
The reason for that is "get" operations must be covariant,
and "set" operations must be contravariant.
The only way for a property to satisfy both requirements is to be invariant.
</simpara>
<simpara>
As of PHP 8.4.0, with the addition of abstract properties (on an interface or abstract class) and
<link linkend="language.oop5.property-hooks.virtual">virtual properties</link>,
it is possible to declare a property that has only a get or set operation.
As a result, abstract properties or virtual properties that have only a "get" operation required may be covariant.
Similarly, an abstract property or virtual property that has only a "set" operation required may be contravariant.
</simpara>
<simpara>
Once a property has both a get and set operation, however,
it is no longer covariant or contravariant for further extension.
That is, it is now invariant.
</simpara>
<example>
<title>Property type variance</title>
<programlisting role="php">
<![CDATA[
<?php
class Animal {}
class Dog extends Animal {}
class Poodle extends Dog {}
interface PetOwner
{
// Only a get operation is required, so this may be covariant.
public Animal $pet { get; }
}
class DogOwner implements PetOwner
{
// This may be a more restrictive type since the "get" side
// still returns an Animal. However, as a native property
// children of this class may not change the type anymore.
public Dog $pet;
}
class PoodleOwner extends DogOwner
{
// This is NOT ALLOWED, because DogOwner::$pet has both
// get and set operations defined and required.
public Poodle $pet;
}
?>
]]>
</programlisting>
</example>
</sect2>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
|