What are the advantages of using a Dependency Container in managing class dependencies in PHP projects?

When working on PHP projects, managing class dependencies manually can become complex and error-prone. A Dependency Container helps simplify this process by centralizing the creation and management of objects, allowing for easier testing, reusability, and flexibility in the codebase.

// Using a Dependency Container to manage class dependencies

class Container {
    private $dependencies = [];

    public function add($name, $resolver) {
        $this->dependencies[$name] = $resolver;
    }

    public function get($name) {
        if(isset($this->dependencies[$name])) {
            return $this->dependencies[$name]();
        }
        throw new Exception("Dependency not found: {$name}");
    }
}

// Usage example
$container = new Container();

$container->add('db', function() {
    return new Database();
});

$container->add('user', function() use ($container) {
    return new User($container->get('db'));
});

$user = $container->get('user');