Hi internals,

During my regular open source work, I realized that PHP yet do not support
contravariance and covariance for user classes.

Some examples that I found that could be really easy to implement and
useful to end user are highlighted here:

- contravariance.php - https://3v4l.org/I3v0u
- covariance.php - https://3v4l.org/i79O5

For all those lazy people that don't want to open 2 new tabs to understand
what I mean, here's a more elaborate example covering both scenarios:

<?php

class A {}

class B extends A {}

class Foo {
    public function bar(B $b) : A {}
}

class Woo extends Foo {
    public function bar(A $b) : B {}
}

$w = new Woo();

Basically, here are the highlights:
- method arguments are ok to reference wider parameter types (and we just
approved the PR for Parameter Type Widening) - this is what we call
contravariant, as contra inheritance direction
- return types are ok to enforce strictness for subtypes - this is what we
call covariant, as Woo is a subtype of Foo

I've walked through PHP source and it looks like the only needed place to
modify is
https://github.com/php/php-src/blob/master/Zend/zend_inheritance.c#L184,
which would require to be decoupled in 2 functions to check which direction
is should support (covariance or contravariance).

Is there anything else that I am missing? I'm happy to write an RFC for
that... =)

Cheers,

-- 
Guilherme Blanco
Senior Technical Architect at Huge Inc.

Reply via email to