What are some best practices for handling recursive class instantiation in PHP?

When dealing with recursive class instantiation in PHP, it's important to handle it carefully to avoid infinite loops or excessive memory usage. One common approach is to use lazy loading or dependency injection to defer instantiation until needed. Another method is to check if the class has already been instantiated before attempting to create a new instance. Additionally, setting a maximum recursion depth can help prevent excessive nesting.

class MyClass {
    private static $instances = [];

    public static function getInstance($className) {
        if (!isset(self::$instances[$className])) {
            self::$instances[$className] = new $className();
        }

        return self::$instances[$className];
    }
}

// Example usage
$instance1 = MyClass::getInstance('MyClass');
$instance2 = MyClass::getInstance('MyClass');