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:
But reason for a untyped method/property can also be:
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:
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: