Switch by class (instanceof) in PHP

Switch by class (instanceof) in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Switch by class (instanceof) in PHP

Replacing a chain of if or elseif statements that use instanceof checks with a switch statement is a common request from developers seeking cleaner control flow. While PHP supports this syntactic pattern, the underlying mechanics differ significantly from languages like C#, where such switches operate on enum types or specific object instances. In PHP, a standard switch does not natively evaluate type information; it evaluates values. Attempting to force this behavior often leads to verbose and error-prone code.

The core technical limitation lies in how PHP handles the comparison operators within a switch. A switch statement expects expressions that resolve to specific scalar values or objects for strict comparison. When you try to check if an object belongs to a class inside a switch, you are effectively trying to compare the type of the variable against a string representing that type, rather than comparing the object's identity.

Consider the following attempt to replicate the logic from your source example:

class SomeClass {}
class SomeAnotherClass {}

$class = new SomeClass();

// This syntax is invalid in PHP
switch ($class) {
    case instanceof SomeClass: // SyntaxError
        break;
}

This approach fails immediately because case expects a value to compare against, not a type check. You cannot write case instanceof ClassName: as a valid statement. The instanceof operator is fundamentally an expression that returns a boolean, whereas the switch construct looks for equality (== or ===) between the switch subject and its cases.

To achieve type-based routing, you must rely on the fact that in PHP 8.1+, the case keyword supports string comparisons against class names if strict typing is involved, but this does not perform an instanceof check automatically. The most reliable method to simulate a "switch on class" remains an array-based dispatch or a dedicated helper function.

Here is how you can refactor the original if/elseif block into a more scalable pattern without relying on invalid syntax:

function handleObject($class) {
    $handlers = [
        SomeClass::class => fn ($obj) => doSomethingForSomeClass($obj),
        SomeAnotherClass::class => fn ($obj) => doSomethingElse($obj),
    ];

    if (!isset($handlers[$class::class])) {
        throw new InvalidArgumentException("Unsupported class: " . get_class($class));
    }

    return $handlers[$class::class]($class);
}

This pattern leverages the fact that $class::class returns the fully qualified class name as a string. By mapping these strings to closure handlers, you gain the readability of a switch without the syntactic constraints. If you are using PHP 8.1 or higher, you can further optimize this by checking the trait usage or implementing a common interface and switching on that interface name if strict coupling is required, though instanceof checks remain the most explicit way to verify hierarchy.

One critical pitfall when refactoring type checks is handling inheritance hierarchies. In your original example, if $class extends SomeClass, a simple instanceof SomeClass check passes, but a string-based dispatch based on the exact class name would fail unless you explicitly handle parent classes or rely on interface implementation.

If you are working within a Laravel ecosystem and need to route requests based on model types, consider using match (introduced in PHP 8.0) combined with strict type checks for better readability than nested ifs, though still distinct from a native switch. For example:

$handler = match (get_class($class)) {
    SomeClass::class => fn() => doSomethingForSomeClass(),
    SomeAnotherClass::class => fn() => doSomethingElse(),
    default => throw new InvalidArgumentException('Unknown class'),
};

This approach offers better performance than multiple if statements in high-frequency loops and eliminates the cognitive load of nesting. However, it requires that you know all possible classes upfront or have a robust fallback strategy.

Ultimately, while the desire to use switch for type checking is understandable, PHP's design dictates that explicit instanceof checks or string-based dispatch maps are the correct tools for the job.

Our network