What are the best practices for structuring PHP classes and methods to prevent errors like "Call to a member function query() on a non-object"?

The error "Call to a member function query() on a non-object" typically occurs when trying to call a method on an object that is not properly instantiated. To prevent this error, ensure that objects are properly initialized before calling their methods. This can be achieved by using constructor methods or initializing objects within the class.

class Database {
    private $connection;

    public function __construct() {
        $this->connection = new mysqli("localhost", "username", "password", "database");
    }

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

// Example usage
$database = new Database();
$result = $database->query("SELECT * FROM table_name");