Creating PHP class instance with a string

Creating PHP class instance with a string

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

Stefan Bogdanescu

Founder & Senior Architect

Creating PHP Class Instances from Strings Without Switch Statements

In PHP, dynamically instantiating a class based on a string identifier is a common pattern when building factories, dependency injection containers, or plugin architectures. The naive approach often involves a switch statement or an associative array mapping names to classes. While functional, these patterns introduce coupling between your logic and specific class names, making the code harder to maintain and extend.

The core challenge lies in bridging the gap between a string value (e.g., "One") and the actual class definition (ClassOne). PHP provides several mechanisms for this, but each comes with distinct trade-offs regarding performance, security, and readability. The most direct method involves using Reflection, while modern frameworks often abstract this complexity away entirely.

Using Reflection API

The standard library solution is the ReflectionClass interface. This allows you to inspect class information at runtime without hardcoding every possible instantiation path in a control flow statement.

Here is how you can implement this with minimal overhead:

class Factory {
    public static function create(string $name): object
    {
        // Normalize the input string to match the class name casing
        // Assuming 'One' maps to 'ClassOne' and 'Two' maps to 'ClassTwo'
        $className = "Class" . ucfirst($name);

        try {
            $reflection = new ReflectionClass($className);
            
            // Ensure the class exists and is instantiable
            if (!$reflection->isInstantiable()) {
                throw new InvalidArgumentException("Class {$className} cannot be instantiated.");
            }

            return $reflection->newInstanceWithoutConstructor();
        } catch (ReflectionException $e) {
            throw new InvalidArgumentException("Class {$className} does not exist.", 0, $e);
            // Alternatively, handle ReflectionException directly if preferred
        }
    }
}

This approach is robust because it throws a clear ReflectionException if the class doesn't exist, rather than failing silently or requiring a massive switch block. It also validates that the target class allows instantiation via the isInstantiable() check. However, you must ensure that the string manipulation logic (in this case, prepending "Class" and capitalizing) is strictly controlled to prevent arbitrary code execution if user input is passed directly into $name.

The Dependency Injection Alternative

In modern PHP development, particularly within the Laravel ecosystem, manually resolving classes by name is often unnecessary. Frameworks like Laravel provide built-in container systems that handle this logic efficiently and safely. If you are already using a framework or building an application where you can leverage its services, injecting dependencies directly via type hints or using the service provider registration is generally preferred over runtime reflection.

For example, in a Laravel application, you might define your bindings in a Service Provider:

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton('One', ClassOne::class);
        $this->app->singleton('Two', ClassTwo::class);
    }
}

This allows you to resolve instances simply by requesting the key string, offloading the complexity of reflection and error handling to the framework's container. This pattern scales better as your application grows because you don't have to maintain a central factory logic for every new class added.

Security Considerations

Regardless of the method chosen, the primary pitfall is treating the input string as untrusted data. If $str comes from an external source (like a URL parameter), you must validate it against a whitelist of allowed values before constructing the class name or passing it to ReflectionClass. Blindly concatenating strings can lead to fatal errors if a malicious actor tries to instantiate a non-existent class with special characters, potentially causing application crashes.

Always validate $str against a strict set of allowed identifiers (['One', 'Two']) before attempting dynamic resolution. This ensures that your application fails gracefully with a predictable error message rather than exposing internal stack traces or crashing unexpectedly.

Conclusion

While the ReflectionClass API offers a clean, standard-library way to instantiate classes from strings without verbose switch statements, it requires careful input validation and error handling. For new projects or those already using frameworks like Laravel, leveraging the dependency injection container is often the superior architectural choice, providing better decoupling and easier maintenance as the codebase expands.

Our network