How can one ensure that methods within a PHP class are properly instantiated and called for database operations?

To ensure that methods within a PHP class are properly instantiated and called for database operations, you can create a database connection within the class constructor and use it in the class methods. This way, you can ensure that the database connection is established before any database operation is performed and properly closed after the operation is completed.

class Database {
    private $conn;

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

    public function fetchUserById($id) {
        $query = "SELECT * FROM users WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();
        return $user;
    }

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

// Usage
$db = new Database('localhost', 'username', 'password', 'database');
$user = $db->fetchUserById(1);
$db->closeConnection();