DEV Community

Cover image for Why `mixed` Is the Worst Type in Your PHP Codebase (and How to Kill It)
Gabriel Anhaia
Gabriel Anhaia

Posted on

Why `mixed` Is the Worst Type in Your PHP Codebase (and How to Kill It)


A team I talked to last month had 1,400 mixed return types across their Laravel 11 codebase. PHPStan level 6 was green. Tests passed. A junior dev refactored one helper, and three controllers started returning HTTP 500s in staging. Nothing flagged it. Nothing could.

mixed is the PHP type system saying "I give up." Laravel's own docs sprinkle it everywhere. PHPStan tolerates it through level 7. Your codebase quietly accumulates it. Every mixed is a load-bearing crack you can't see until something downstream snaps.

Five concrete failure modes, then a 50-line script that finds your worst offenders.

What mixed actually means (and why "anything" is the problem)

mixed was added in PHP 8.0 as the explicit version of "no type." It accepts int, string, array, object, null, false, closures, resources. Everything PHP can hold. It's the top type of the language.

Here's the trap: a top type tells you nothing. If a function returns mixed, the caller has to assume the worst case for every branch. Every comparison. Every method call. The compiler (in PHP's case, the static analyser) has no information to work with.

The pre-8.0 alternative was a missing return type, which static tools treated the same way. PHP 8.0 didn't introduce a new problem. It gave the existing problem a name. The name didn't help. It made the problem easier to write down and harder to flag as a code smell.

Failure 1: IDE autocomplete dies on every mixed return

You write $order = $repo->find($id); and hit ->. PHPStorm gives you nothing. Or worse, it gives you every method on every class in your project, sorted alphabetically. You scroll past __construct, accept, acknowledge, actAs...

// Repository.php: the kind of code that ages badly
final class OrderRepository
{
    public function find(int $id): mixed  // <-- the crime
    {
        $row = DB::table('orders')->find($id);
        if (!$row) {
            return null;
        }
        return Order::fromRow($row);
    }
}
Enter fullscreen mode Exit fullscreen mode

The signature says "could be anything." So PHPStorm assumes it is. You lose go-to-definition. You lose rename refactors on Order fields. You lose the warning that says "you're calling ->customerId on a null." You're typing PHP 5.6 in 2026.

The fix is mechanical:

public function find(int $id): ?Order
{
    $row = DB::table('orders')->find($id);
    return $row ? Order::fromRow($row) : null;
}
Enter fullscreen mode Exit fullscreen mode

One word. The IDE wakes up. Rename refactors land everywhere they should. The next dev who reads find() knows what comes back without grepping the body.

Failure 2: PHPStan level 6+ can't catch null deref on mixed

This is the failure mode that bites in production. PHPStan can prove a lot about your code, but mixed is a wall.

public function totalForCustomer(int $customerId): float
{
    $orders = $this->cache->get("orders.$customerId"); // returns mixed
    $sum = 0.0;
    foreach ($orders as $order) {
        $sum += $order->total;
    }
    return $sum;
}
Enter fullscreen mode Exit fullscreen mode

Run PHPStan level 7 on this. It passes. The foreach on mixed, the ->total access on mixed. PHPStan can't reason about either because it has no upper bound. The runtime catches it: Cannot access property total on mixed, but only when the cache misses, which is what you don't catch in tests.

Level 8 is where PHPStan stops being kind. At level 8, calling a method on mixed is a violation. Iterating mixed is a violation. mixed[] access is a violation. The fix is to type the cache wrapper itself:

final class OrderCache
{
    /** @return list<Order> */
    public function getOrders(int $customerId): array
    {
        $raw = $this->store->get("orders.$customerId");
        if (!is_array($raw)) {
            return [];
        }
        return array_map(fn($r) => Order::fromArray($r), $raw);
    }
}
Enter fullscreen mode Exit fullscreen mode

The PHPDoc generic and the runtime check at the boundary do the work. Inside the rest of the codebase, $cache->getOrders($id) is a list<Order>. No mixed. No null deref. PHPStan level 8 stays green.

Failure 3: Generic wrappers (Collection<mixed>) hide nothing

Laravel's Collection is the most-used class in any Laravel codebase. It's also the most lied-to. The default type when you don't add a PHPDoc is Collection<int, mixed>:

public function activeOrders(): Collection
{
    return Order::where('status', 'active')->get();
}
Enter fullscreen mode Exit fullscreen mode

PHPStan sees this as Illuminate\Database\Eloquent\Collection<int, Model> at best, Collection<mixed> if you're using base Collection. The chained calls below all run on mixed:

$activeOrders
    ->filter(fn ($o) => $o->customerId === $id)  // mixed->customerId
    ->map(fn ($o) => $o->total)                  // mixed->total
    ->sum();
Enter fullscreen mode Exit fullscreen mode

Every arrow is a guess. Every refactor (renaming customerId to customer_id, adding a ? to total) silently misses these call sites.

The fix is the PHPDoc generic:

/** @return Collection<int, Order> */
public function activeOrders(): Collection
{
    return Order::where('status', 'active')->get();
}
Enter fullscreen mode Exit fullscreen mode

PHPStan and PHPStorm both honour that annotation. The ->filter callback now gets a typed Order. The ->map returns Collection<int, float>. The ->sum is typed float. Type information flows through the pipeline.

larastan/larastan enables this for Eloquent collections out of the box on level 6+. The catch: you have to write the generic. The default (a Collection with no annotation) is Collection<mixed>. That's where most codebases live.

Failure 4: Refactors break in three places downstream

A small rename illustrates the compounding cost. You have a getConfig() helper returning mixed:

function getConfig(string $key): mixed
{
    return config($key);
}

// Three callers, all using it differently:
$ttl = getConfig('cache.default.ttl');              // expects int
$drivers = getConfig('queue.connections');          // expects array
$timeout = getConfig('http.timeout');               // expects ?int
Enter fullscreen mode Exit fullscreen mode

You decide getConfig is silly (since config() already exists) and delete the helper. The IDE's rename refactor doesn't know any of the call sites are special, because they all consumed mixed. You delete the helper, the call sites fall back to config() directly, and three of them now use the value differently than they should.

Worse: you decide to add validation. getConfig should throw on missing keys:

function getConfig(string $key): mixed
{
    $value = config($key);
    if ($value === null) {
        throw new ConfigMissing($key);
    }
    return $value;
}
Enter fullscreen mode Exit fullscreen mode

Now everywhere that consumed ?int from this function silently changed contract. PHPStan can't help, because mixed accepts both int and ?int. Tests pass. Production throws on first cache-miss after deploy.

The fix here isn't generics. It's: small, single-purpose typed helpers.

final class CacheConfig
{
    public function ttl(string $store): int
    {
        $value = config("cache.stores.$store.ttl");
        if (!is_int($value)) {
            throw new ConfigMissing("cache.stores.$store.ttl");
        }
        return $value;
    }
}
Enter fullscreen mode Exit fullscreen mode

You can't refactor a typed contract without breaking the type system. That's the whole point of types.

Failure 5: mixed in trait method signatures forces every consumer to widen

This one is subtle. A trait method with a mixed return signature poisons every class that uses it:

trait HasMetadata
{
    public function getMetadata(string $key): mixed
    {
        return $this->metadata[$key] ?? null;
    }
}

final class Order
{
    use HasMetadata;

    public function shippingAddress(): Address
    {
        $raw = $this->getMetadata('shipping');  // mixed
        return Address::fromArray($raw);        // PHPStan: ok, mixed accepts array
    }
}
Enter fullscreen mode Exit fullscreen mode

PHPStan level 8 flags Address::fromArray($raw) because $raw is mixed and fromArray expects array. To silence it, the dev adds a runtime cast: assert(is_array($raw)). That works, but it's a runtime tax for a type system failure.

The real fix is to remove mixed from the trait by making the trait generic via PHPDoc:

/**
 * @template TValue
 */
trait HasMetadata
{
    /** @var array<string, TValue> */
    private array $metadata = [];

    /** @return TValue|null */
    public function getMetadata(string $key)
    {
        return $this->metadata[$key] ?? null;
    }
}

final class Order
{
    /** @use HasMetadata<string|array<string, string>> */
    use HasMetadata;
}
Enter fullscreen mode Exit fullscreen mode

PHPStan honours @template on traits. The consumer pins the type. The mixed is gone from the call sites without runtime asserts.

Traits are where mixed accumulates fastest, because they're framework-y and "reused." Every reuse propagates the weakest signature.

The replacement ladder: mixed to union to interface to concrete type

When you find mixed in your code, climb this ladder:

  1. Concrete type: if you can write Order, write Order. Never settle for less.
  2. Nullable concrete: ?Order if the method can legitimately return nothing.
  3. Union: Order|Refund|null when the function returns one of a few things. Discriminated unions are PHP's way of saying "one of these."
  4. Interface: Refundable if you care about behaviour, not class identity.
  5. PHPDoc generic: list<Order>, array<string, Money>, Collection<int, Order>. PHPStan understands these.
  6. mixed: only at trust boundaries (deserialising JSON, reading from $_POST, hitting a cache before validation). And then immediately narrow, before passing the value anywhere else.

Rule of thumb: mixed should live in your codebase for one line. The line after it should narrow.

A 50-line audit script that finds your worst mixed offenders

You don't need PHP-Parser for the first pass. Grep with the right pattern gets you 90% of the way there. Save this as bin/audit-mixed.sh:

#!/usr/bin/env bash
# audit-mixed.sh: rank files by mixed-density
set -euo pipefail

ROOT="${1:-src}"
TMP=$(mktemp)

# count mixed occurrences per file, ignoring vendor/tests
find "$ROOT" -name '*.php' \
    -not -path '*/vendor/*' \
    -not -path '*/tests/*' \
    -print0 \
  | while IFS= read -r -d '' file; do
      # match `: mixed` returns, `mixed $var` params, `@param mixed`,
      # `@return mixed`, and `@var mixed` PHPDoc tags
      count=$(grep -cE '(\:\s*mixed\b|mixed\s+\$|@(param|return|var)\s+mixed)' "$file" || true)
      lines=$(wc -l < "$file")
      if [ "$count" -gt 0 ]; then
          # density = mixed count per 100 lines
          density=$(awk "BEGIN { printf \"%.2f\", ($count * 100) / $lines }")
          printf '%s\t%d\t%d\t%s\n' "$density" "$count" "$lines" "$file" >> "$TMP"
      fi
  done

echo "DENSITY  COUNT  LINES  FILE"
echo "-----------------------------"
sort -rn "$TMP" | head -30
rm "$TMP"
Enter fullscreen mode Exit fullscreen mode

Run it: ./bin/audit-mixed.sh src. You get the 30 worst offenders sorted by mixed-density-per-100-lines. Density matters more than raw count. A 2000-line model with 8 mixed is healthier than a 50-line trait with 6.

For the PHP-Parser version (more accurate, catches dynamic property access and ignores comments), nikic/php-parser 5.x plus a NodeVisitorAbstract that counts Identifier nodes named mixed inside Stmt\ClassMethod and Stmt\Function_. The bash version is what you want for a CI check. Add a line that fails the build if the top file's density crosses a threshold you commit to (start at 3.0, ratchet down monthly).

PHPStan level 8 is the enforcement

The audit tells you where you stand. PHPStan level 8 keeps you there.

In phpstan.neon:

parameters:
    level: 8
    paths:
        - src
    ignoreErrors: []
    treatPhpDocTypesAsCertain: true
    checkMissingIterableValueType: true
    checkGenericClassInNonGenericObjectType: true
Enter fullscreen mode Exit fullscreen mode

Level 8 forbids:

  • Method calls on mixed
  • Property access on mixed
  • Array access on mixed
  • Foreach over mixed
  • Returning mixed from a function whose declared return is more specific

It allows mixed itself as a declared type (PHP allows it, PHPStan won't fight the language). But it forces you to narrow before use. Combined with the audit script, you get steady forward progress: PHPStan stops new mixed from being added in unsafe ways; the audit pressures the team to delete the old ones.

The team I mentioned at the top moved 1,400 mixed returns to 280 over a quarter. Their HTTP 500 rate from type errors dropped to near-zero. The PHPStan baseline file shrunk every week. Nobody wrote a single line of new validation code. They just typed what was already there.

mixed is the easiest type to write. It's the most expensive to keep.

What's the worst mixed you've ever inherited? Drop the density score from audit-mixed.sh in the comments.


If this was useful

The mixed problem is a symptom: framework defaults that lean on dynamic typing leak into the domain code where they don't belong. The fix is a clean boundary between the framework layer and the typed core. Decoupled PHP is the architectural layer your codebase reaches for after it outgrows the framework defaults: repository interfaces, value objects, use cases that never see a mixed.

Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework

Available on Kindle, Paperback, and Hardcover. English, German, and Japanese editions out now — Portuguese and Spanish coming soon.

Top comments (0)