Skip to content
PHP Logo

How can dependency injection be utilized to access configuration settings in PHP classes?

When using dependency injection in PHP classes, configuration settings can be accessed by passing a configuration object or array as a dependency to the class constructor. This allows the class to retrieve the necessary configuration settings without directly accessing them from a global scope or configuration file, making the code more modular and testable.

php
<?php

class DatabaseConnection {
    private $config;

    public function __construct(array $config) {
        $this->config = $config;
    }

    public function connect() {
        $dsn = "mysql:host={$this->config['host']};dbname={$this->config['database']}";
        $username = $this->config['username'];
        $password = $this->config['password'];

        // Connect to the database using $dsn, $username, and $password
    }
}

// Configuration settings
$config = [
    'host' => 'localhost',
    'database' => 'my_database',
    'username' => 'root',
    'password' => 'password'
];

// Instantiate DatabaseConnection class with configuration settings
$databaseConnection = new DatabaseConnection($config);

// Use the database connection
$databaseConnection->connect();