Why is it recommended to define $query as a class variable rather than creating it anew in each method in PHP?

Defining $query as a class variable rather than creating it anew in each method in PHP is recommended because it allows for better performance and reusability. When $query is defined as a class variable, it only needs to be instantiated once and can be accessed by any method within the class. This prevents unnecessary overhead of creating a new instance of $query every time a method is called, resulting in improved efficiency.

class Database {
    private $connection;
    private $query;

    public function __construct($connection) {
        $this->connection = $connection;
        $this->query = new Query(); // Instantiate $query object
    }

    public function executeQuery($sql) {
        return $this->query->execute($this->connection, $sql);
    }

    // Other methods using $this->query
}