Let me share with you my experience:
I have a 3G and for a while it would start to shut down on it's own. The few times I caught it, you could even see that it would display the "turn off" slide like if I was holding the off button and then shut down by itself. This situation went on for a while, slowly getting worse. Eventually, I could not get it to even stay on or restart after shut down. I tried to restore, jailbreak, etc... to no avail. At the end, the off button was no longer working, or more like working all the time, like if it was stuck pushed in (which was not the case).
I did notice two peculiar things, however:
1- when I had the iphone plugged to the power, it would not shut down by itself.
2- when the first symptoms appeared, I would notice that the phone was getting hot while in use.

Eventually, I decided to change the battery and it fixed it all.
I don't know if the phone has a safeguard that makes it turn off if the battery is failing but that fixed it for me.