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();
Related Questions
- What is the function for rounding in PHP and where can you find more information about it?
- What common mistakes or errors can occur when programming a contact form in PHP, as seen in the provided code snippet?
- What are the potential pitfalls of not properly escaping user input in SQL queries in PHP?