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.
<?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
mixed
type accepts any value type, so it cannot be used as part of the union types. For example,string|mixed
is illegal. - When a parameter or property doesn't have a type declaration, PHP assumes that is
mixed
type. - When the return value doesn't have a type declaration, PHP assumes that is
mixed|void
type. However, we cannot specifymixed|void
type for return value becausemixed
type is not allowed as part of the union types. - The
mixed
type accepts any value type, includingnull
. Somixed
cannot be specified as nullable. It means that?mixed
ormixed|null
are not allowed. - We cannot cast a variable to
mixed
type. For example,$value = (mixed) $value;
emits a parse error.
Leave a Comment
Cancel reply