In PHP, what are some alternative methods to dynamically instantiate classes with varying constructor parameters without modifying the class methods themselves?

When needing to dynamically instantiate classes with varying constructor parameters without modifying the class methods themselves, one approach is to use reflection to inspect the class constructor and pass arguments accordingly. Another method is to define a factory method that handles the instantiation logic based on the input parameters.

class MyClass {
    private $param1;
    private $param2;

    public function __construct($param1, $param2) {
        $this->param1 = $param1;
        $this->param2 = $param2;
    }
}

function createInstance($className, $params) {
    $reflection = new ReflectionClass($className);
    $instance = $reflection->newInstanceArgs($params);
    return $instance;
}

$instance = createInstance('MyClass', [1, 'example']);