Because both headphones and microphones have a diaphragm consisting of a coil wrapped around. When you speak through it, your voice makes it vibrate to generate current from the opposite end. Using your headphones as a microphone, however, won't sound as great, though.