Understanding how microbes gather into biofilm communities and maintain diversity remains one of the central questions of microbiology, requiring an understanding of microbes as communal rather then individual organisms. Phase variation plays an integral role in the formation of diverse phenotypes within biofilms. We propose a collective mechanism for phase variation based on gene transfer agents, and apply the theory to predict the population structure and growth dynamics of a biofilm. Our results describe quantitatively recent experiments, with the only adjustable parameter being the rate of intercellular horizontal gene transfer. Our approach derives from a more general picture for the emergence of cooperation between microbes.