PHP supports type declarations that can be used for parameters, return values, and properties. However, there may be situations when we need a type that is not supported by PHP yet. We can omit type declaration, but this can cause ambiguous meaning. For example, the developer forgot to specify type declaration, developer omitted type declaration to keep code compatible with old PHP versions, etc.
Since PHP 8.0, we can use a new mixed type. It is equivalent to the following union type:
array|bool|callable|int|float|object|resource|string|null
We can use mixed type anywhere types are accepted: parameters, return values, and properties.
Container.php
<?php
class Container
{
private mixed $value;
public function getValue(): mixed
{
return $this->value;
}
public function setValue(mixed $value): void
{
$this->value = $value;
}
}
There are some important notes:
- The
mixedtype accepts any value type, so it cannot be used as part of the union types. For example,string|mixedis illegal. - When a parameter or property doesn't have a type declaration, PHP assumes that is
mixedtype. - When the return value doesn't have a type declaration, PHP assumes that is
mixed|voidtype. However, we cannot specifymixed|voidtype for return value becausemixedtype is not allowed as part of the union types. - The
mixedtype accepts any value type, includingnull. Somixedcannot be specified as nullable. It means that?mixedormixed|nullare not allowed. - We cannot cast a variable to
mixedtype. For example,$value = (mixed) $value;emits a parse error.
Leave a Comment
Cancel reply