What are the potential issues with using PDO in a class in PHP?
One potential issue with using PDO in a class in PHP is that it can lead to tightly coupled code, making it harder to maintain and test. To solve this, you can inject the PDO connection into the class through its constructor or a setter method, allowing for better separation of concerns.
class Database {
private $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function query($sql) {
return $this->pdo->query($sql);
}
}
// Usage
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);
$result = $database->query('SELECT * FROM table');
Keywords
Related Questions
- How can PHP beginners avoid common errors like variable initialization and handling undefined variables in their code?
- Are there any specific functions in PHP that can help prevent error messages in foreach loops?
- What are the best practices for handling audio recordings in PHP contact forms to ensure proper encoding and playback?