Why is passing the PDO connection object as a parameter preferred over using self:: in PHP classes for database operations?

Passing the PDO connection object as a parameter is preferred over using self:: in PHP classes for database operations because it allows for better flexibility and reusability. By passing the connection object as a parameter, the class is not tightly coupled to a specific database connection, making it easier to switch between different databases or mock the connection for testing purposes. Additionally, it promotes better separation of concerns and improves the overall readability of the code.

class DatabaseOperations {
    private $pdo;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }

    public function fetchData() {
        $stmt = $this->pdo->query('SELECT * FROM table');
        return $stmt->fetchAll();
    }
}

// Usage
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$databaseOperations = new DatabaseOperations($pdo);
$data = $databaseOperations->fetchData();