How can static class variables be effectively used to maintain database connections in PHP classes?
To maintain database connections in PHP classes using static class variables, you can create a static variable within the class to store the database connection object. This ensures that only one connection is established and reused across all instances of the class. By using a static variable, you can easily access the database connection without the need to repeatedly create new connections.
class Database {
private static $connection;
public static function getConnection() {
if (!self::$connection) {
self::$connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
}
return self::$connection;
}
}
// Example of how to use the static database connection
$connection = Database::getConnection();
$stmt = $connection->prepare("SELECT * FROM users");
$stmt->execute();