Mixed Pseudo Type in PHP 8

The mixed type in PHP 8 is a new built-in union type that accepts any value type. It represents the union of array|bool|callable|int|float|string|object|null|resource, making it more explicit than omitting type declarations entirely.

The mixed type indicates that a parameter, return value, or property can accept any PHP type, providing better code documentation and IDE support compared to having no type declaration at all.

Syntax

function functionName(mixed $parameter): mixed {
    // Function body
}

class ClassName {
    public mixed $property;
}

Equivalent Union Type

The mixed type is equivalent to this union type −

int|float|bool|string|null|array|object|callable|resource

Basic Example

Here's how to declare mixed types in class properties and methods −

<?php
   class Student {
       public mixed $studentProperty;
       
       public function setData(mixed $data): mixed {
           $this->studentProperty = $data;
           return $this->studentProperty;
       }
   }
   
   $student = new Student();
   $student->studentProperty = "Hello World";
   echo $student->studentProperty . "<br>";
   
   $student->studentProperty = 42;
   echo $student->studentProperty . "<br>";
   
   $student->studentProperty = [1, 2, 3];
   print_r($student->studentProperty);
?>
Hello World
42
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

Mixed Type with Variadic Parameters

The mixed type works well with variadic parameters to accept multiple arguments of different types −

<?php
   function debug_function(mixed ...$data) {
       foreach ($data as $index => $value) {
           echo "Argument $index: ";
           var_dump($value);
       }
   }
   
   debug_function(10, 'string', [], true, null);
?>
Argument 0: int(10)
Argument 1: string(6) "string"
Argument 2: array(0) {
}
Argument 3: bool(true)
Argument 4: NULL

Important Restrictions

The mixed type has several important limitations −

Cannot Be Cast

You cannot cast a variable to mixed type as it doesn't represent a specific type −

$foo = (mixed) $bar; // Invalid - causes error

Cannot Be Used in Union Types

Mixed cannot be combined with other types in union declarations −

<?php
// This will cause a fatal error
function example(mixed|string $param): int|mixed {
    return $param;
}
?>
Fatal error: Type mixed can only be used as a standalone type

Not Returned by Type Functions

The gettype() and get_debug_type() functions will never return "mixed" as they return the actual runtime type of a variable.

Conclusion

The mixed type in PHP 8 provides explicit documentation for functions and properties that can accept any type, improving code clarity over omitted type declarations. Remember that mixed must be used standalone and cannot be combined with other types in unions.

Updated on: 2026-03-15T09:42:13+05:30

812 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements