rfc:strict_return_types

PHP RFC: Strict return types

Introduction

Weak return types were added alongside with weak scalar parameter types. But that violates the principle of “weak in, strict out”. Return types should always be strictly checked. I know what I want to return, thus the return type should check whether I really returned what I wanted instead of trying to cast.

Proposal

This RFC proposes always strict checking of return types - regardless of any declare(strict_types) instruction.

Scalar return types were introduced in a way to be consistent with parameter types: any passed (to a function) or returned variables (from a function) would be type checked equally strictly or weakly inside a file depending on the strict_types declaration.

But that wasn't a wise choice. You always want to have strict return types, but possibly have weak types when calling a function. While you may not have full control over a called function, you have full control over a function you defined yourself - and may just explicitly add a type cast when returning. Return types really should be able to prove correctness of the returned value instead of silently casting.

Backward Incompatible Changes

Current weak return types will break. This shouldn't be too much of an issue though, as a) the share of weak return types intentionally used for casting should be very, very low and b) return types only officially are available since exactly three months (as of initial writing of this RFC), so not much PHP 7-only code will exist.

Proposed PHP Version(s)

PHP 7.1.

And we additionally should soft-deprecate this in documentation as soon as this RFC passes to avoid more people relying on that behavior.

Unaffected PHP Functionality

Function parameter scalar types are not changed.

Future Scope

This sections details areas where the feature might be improved in future, but that are not currently proposed in this RFC.

Proposed Voting Choices

Yes/no vote with 2/3 majority required.

Patches and Tests

No patch yet, but implementation is trivial - will be added later.

References

rfc/strict_return_types.txt · Last modified: 2017/09/22 13:28 (external edit)