How can I avoid having to re-establish the database connection every time I call a function in my PHP class?

To avoid having to re-establish the database connection every time you call a function in your PHP class, you can establish the connection once in the constructor of your class and store the connection object as a class property. This way, the connection will be available to all methods within the class without the need to reconnect each time.

class DatabaseConnection {
    private $connection;

    public function __construct() {
        $this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    }

    public function fetchData() {
        $query = $this->connection->query('SELECT * FROM mytable');
        return $query->fetchAll();
    }

    // Other methods that can use the $this->connection property
}

// Usage
$database = new DatabaseConnection();
$data = $database->fetchData();