Quantcast
Channel: User bdsl - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by bdsl for Can parameter types be specialized in PHP

$
0
0

The code shown in the question is not going to compile in PHP. If it did class Bar would be failing to honour the gurantee made by it's parent Foo of being able to accept any instance of TypeA, and breaching the Liskov Substitution Principle.

Currently the opposite code won't compile either, but in the PHP 7.4 release, expected on November 28 2019, the similar code below will be valid, using the new contravariant arguments feature:

abstract class Foo {    public abstract function run(TypeB $object); // TypeB extends TypeA}class Bar extends Foo {    public function run(TypeA $object) {        // Some code here    }}

All Bars are Foos, but not all Foos are Bars. All TypeBs are TypeAs but not all TypeAs are TypeBs. Any Foo will be able to accept any TypeB. Those Foos that are also Bars will also be able to accept the non-TypeB TypeAs.

PHP will also support covariant return types, which work in the opposite way.


Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>