rfc:allow-void-variance

This is an old revision of the document!


PHP RFC: Your Title Here

Introduction

This RFC proposes to change 'void' 's behavior in class methods, because the current behavior resulted to cause more annoyance than benefit. What is proposed is backward compatible and in accordance with the goals of the previous RFC; it eliminates pointless restrictions.

Rationale

The intent of 'void' should be simply making clear to the reader that the function does not return anything useful, and that any attempt to use the returned value should be considered a bogus operation; it shouldn't do more than that.

Currently, it also denies a void method to be overridden with a different type in subclasses.

class Foo{
    function method (): void  {}
}
 
class Bar extends Foo{
    function method (): array { return []; } // fails
}
 
class Baz extends Foo{
    function method ()        { return 42; } // also fails
}

This should be allowed, because it is causing a lot of discontent and, most importantly, because it achieves nothing at all.

function myFooConsumer (Foo $foo) {
 
   // method() is void, therefore we shouldn't be using its return type
 
   $foo->method();
}

If a 'Bar' object is passed to the function (i.e. 'myFooConsumer(new Bar())'), even if 'Bar::method()' returns an 'array', it is not breaking the code in 'myFooConsumer', because the function 'myFooConsumer' has no interest in the return value of 'method()' at all.

Even if it's receiving a 'Bar' object, the function is written to be compatible with 'Foo' objects. The 'method()' can return anything, or nothing at all, but 'myFooConsumer' does not care about it.

Proposal

This RFC proposes to allow 'void' to be changed to any type or mixed in sub classes.

rfc/allow-void-variance.1549246623.txt.gz · Last modified: 2019/02/04 02:17 by wesnetmo