apache hang on deadlock
MySQL has built in deadlock detection and detects a deadlock as soon as it occurs.  If you need to detect deadlocks, you will have to examine the error message coming back from the failed transaction, or use pt-deadlock-logger to log deadlocks external to the application.

The code you have supplied doesn't detect deadlocks.  It detects failed transactions and retries 3 times.  If the transaction took a long time, you will occupy an apache worker for three times as long as the transaction took.  If the failure occurs due to a lock timing out (note locks and deadlocks are very different), the code above could take up to 2.5 minutes to return to the browser, assuming you have innodb_lock_wait_timeout set to the default of 50 seconds.  That's a long long time.

Can we step back and ask what is it that you are trying to accomplish with this code path?

(side note, I think this belongs on stackoverflow, not here as this seems more like a PHP/development question).