How can static access be avoided in PHP for better testability and maintainability?

Static access in PHP can be avoided by using dependency injection. This means passing dependencies into a class through its constructor or setter methods, rather than accessing them statically. This approach improves testability as it allows for easier mocking of dependencies during unit testing and enhances maintainability by reducing tight coupling between classes.

// Avoid static access by using dependency injection

class DatabaseConnection {
    private $host;
    private $username;
    private $password;

    public function __construct($host, $username, $password) {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
    }

    public function connect() {
        // Database connection logic using $this->host, $this->username, $this->password
    }
}

// Usage example
$host = 'localhost';
$username = 'root';
$password = 'password';

$connection = new DatabaseConnection($host, $username, $password);
$connection->connect();