PHP 8.0 : `mixed` type
21, August 2021

Type system before PHP 7.0 era was...ummm...not so good. If you ever worked in a project that was built in PHP 5.*, you will notice that they hardly contain any type related info. Even if you can define types via docblock, many devs just ignore them or forget to update them. If you need to modernize such legacy project, you will have to fight with codebase to figure out parameter/return types of some methods. Some methods do so much work in themselves that they accepts and returns multiple types of data. In some places you might have to keep them untyped because:

  • Method intentionally deals with almost all types of data
  • It's very hard to predict what type of data this method works with (very common with large legacy projects)
  • They type is not yet well defined in PHP, so dev ignored it for now
  • Project needs to be compatible with older version of PHP

But reason for a untyped method/property can also be:

  • Dev forgot to define it
  • Dev simply didn't care


So, why do we need mixed type again?

When you are working on a project and you find a untyped method/property, its not easy to know why that method/property is untyped. Is it intentional? or is it mistake by previous dev? This confusion can be real pain when trying to modernize any legacy project.

We can use mixed type to ease this confusion. If a method/property is defined as mixed type, that means that type wasn't forgotten about. Mixed type can be a signal that it was defined that way intentionally, maybe because of the reasons we talked about in first section.

<?php

class Foo {

private mixed $property;

public function bar(mixed $input): mixed
{
    // method accepts all type of data and returns any type of data
}


mixed type is actually a collections of other available types. A type of mixed would be equivalent to array|bool|callable|int|float|null|object|resource|string


Note:

  • mixed type can't be used together with void, so mixed|void union type is not allowed
  • As mixed type already contains null type, nullable mixed type is not supported. So we can't use ?mixed


Last but not the least, Please refrain from using mixed type on new code. Define type in as much place as you can to save yourself from future headache.


Write comment about this article: