Skip to content
PHP Logo

How can object-oriented programming (OOP) principles be applied to improve PHP code, specifically in the context of database connections?

To improve PHP code related to database connections using OOP principles, we can create a Database class that encapsulates the database connection logic. This helps in promoting code reusability, maintainability, and separation of concerns.

php
class Database {
    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'my_database';
    private $connection;

    public function __construct() {
        $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
        if ($this->connection->connect_error) {
            die("Connection failed: " . $this->connection->connect_error);
        }
    }

    public function getConnection() {
        return $this->connection;
    }

    public function closeConnection() {
        $this->connection->close();
    }
}

// Example of using the Database class
$database = new Database();
$connection = $database->getConnection();

// Perform database operations using $connection

$database->closeConnection();