In conventional photovoltaic solar cells, photogenerated carriers are extracted by the built-in electric field of a semiconductor PN junction, defined by ionic dopants. In atomically thin semiconductors, the doping level can be controlled by the field effect, enabling the implementation of electrically tunable PN junctions. However, most two-dimensional (2D) semiconductors do not show ambipolar transport, which is necessary to realize PN junctions. Few-layer black phosphorus (b-P) is a recently isolated 2D semiconductor with direct bandgap, high mobility, large current on/off ratios and ambipolar operation. Here we fabricate few-layer b-P field-effect transistors with split gates and hexagonal boron nitride dielectric. We demonstrate electrostatic control of the local charge carrier type and density in the device. Illuminating a gate-defined PN junction, we observe zero-bias photocurrents and significant open-circuit voltages due to the photovoltaic effect. The small bandgap of the material allows power generation for illumination wavelengths up to 940 nm, attractive for energy harvesting in the near-infrared.