They protect themselves — which is the whole point of a hedgehog's spines, and the reason Sonic's quills work the same way.
Real hedgehogs have thousands of stiff, hollow spines made of keratin, and the defence is passive: a predator that bites down gets a mouthful of sharp points. The hedgehog rolls into a ball and the spines do the rest. There is no attack involved, just a surface nobody wants to grab.
Sonic borrows the idea and turns it into a mechanic. In most games his quills are what let him defeat enemies by jumping into them or homing onto them — the same principle, weaponised. It is a neat bit of design, because it takes a real animal trait and makes it the core verb of the game.
Environmental spikes are a different matter, incidentally. Those hurt Sonic regardless of his quills, which is a small inconsistency the series has never bothered to explain and probably never will.