rfc:mixed-typehint

PHP RFC: Mixed typehint

Introduction

With the addition of scalar types in PHP 7, nullables in 7.1 and recently object in 7.2, it's now possible to explicitly declare accepted types for most of the parameters and return types. Unfortunately without mixed type it's still not possible to achieve a fully type hinted and consistent code using simple types.

Proposal

This RFC proposes to add the mixed type to be used for parameter and return types to explicitly declare desired type, instead of being forced to not declare anything.

Primary motivation for having explicit mixed type is consistence and easier static analysis. In PHP 7.2, mixed types are unfortunately the only type that could not be type hinted upon (and resource as well, but its future is unclear). Having mixed type would allow a code with 100% type coverage in most cases.

The behavior of the mixed type fully matches the behavior when nothing is specified for parameter or return type (thus being implicitly mixed), effectively being an alias for previous behavior.

Nullability

As the mixed type accepts anything, including null, nullable mixed type (?mixed) is disabled at compile time.

function foo(): ?mixed {}
// Fatal error

Variance

No changes to variance needed. Exactly same rules as when no type is present apply.

Since the mixed type and no type are functionally equivalent, the following code is functionally equivalent as well:

function foo($arg) {
    return $arg;
}

and

function foo(mixed $arg): mixed {
    return $arg;
}

Same applies to inheritance, where mixed type and no type could be interchanged without any error. This code would work just fine:

class Foo {
    public function test(mixed $arg): mixed {
        return $arg;
     }
}
class Bar extends Foo {
    public function test($arg) {
        return parent::test($arg);
    }
}
class Baz extends bar {
    public function test(mixed $arg): mixed {
        return parent::test($arg);
    }
}

Backward Incompatible Changes

None, mixed is already reserved word since PHP 7.0.

Proposed PHP Version(s)

7.3

RFC Impact

To SAPIs

None.

To Existing Extensions

None.

To Opcache

Not analyzed.

Unaffected PHP Functionality

No changes to type cast operators.

Proposed Voting Choices

Simple yes/no vote to either accept or reject addition of mixed type. As this is a language change, 2/3 majority is required.

Patches and Tests

References

rfc/mixed-typehint.txt · Last modified: 2017/12/19 03:03 by majkl