What best practices should be followed when passing arguments to class methods in PHP, especially when dealing with database operations?
When passing arguments to class methods in PHP, especially when dealing with database operations, it is important to follow best practices to ensure security and maintainability. One common practice is to use parameterized queries to prevent SQL injection attacks. Additionally, it is recommended to validate and sanitize user inputs before passing them to database queries to avoid potential vulnerabilities.
class DatabaseHandler {
private $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function getUserById($userId) {
$stmt = $this->db->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
// Example of passing arguments safely
$db = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$handler = new DatabaseHandler($db);
$user = $handler->getUserById($_GET['id']);