How can the use of variadic functions in PHP impact the handling of dynamic query parameters in a custom database class?
Using variadic functions in PHP can simplify the handling of dynamic query parameters in a custom database class by allowing for a variable number of parameters to be passed to query functions. This means that the class can accommodate different numbers of parameters without needing to define multiple functions for each case. By using variadic functions, the database class can dynamically construct queries based on the parameters provided, making the code more flexible and easier to maintain.
class CustomDatabase {
private $connection;
public function __construct($connection) {
$this->connection = $connection;
}
public function query($sql, ...$params) {
$stmt = $this->connection->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
}
}
// Example usage
$connection = new PDO("mysql:host=localhost;dbname=test", "username", "password");
$database = new CustomDatabase($connection);
$results = $database->query("SELECT * FROM users WHERE id = ? AND status = ?", 1, 'active');