24

What does register_shutdown_function do?

I have no understanding whatsoever on the usage of it and what it does. I know you can use it and fit nicely with a custom error handler, but I don't know what to pass through it, what to do with it, etc.

Could someone explain it in the easiest terms for this coding newbie?

0

2 Answers 2

44

This is actually a pretty simple function. So you have a php script:

<?php
  echo "Here is my little script";

  function endScript(){
       echo "My little Script has finished";
  }

  register_shutdown_function('endScript');

?>

Basically what happens is your script runs and when it's finished because we added this line register_shutdown_function('endScript'); it will call the function endScript and finally output My little script has finished.

Here's a little extra from the documentation:

Registers a callback to be executed after script execution finishes or exit() is called.Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

*Update

A great use for it is when you frequently use the function called exit() in php.

For example:

<?php 

  function endScript(){
       echo "My little Script has finished";
  }
  register_shutdown_function('endScript');

  $result = some_intricate_function()

  if($result == 0){
     exit();
  } 

  $result = some_other_intricate_function()

  if($result == 0){
     exit();
  }

/* and this keeps reoccurring */
?>

Now notice that even though you call exit multiple times you don't have to call the endScript function before exit each time. You registered it in the begining and now you know that if you ever exit or your script finishes then your function is called.

Now of course my shutdown function is pretty useless; but it can become useful if you need to clean things (ie. Close open file handles, save some persistent data, etc)

3
  • I understand it now! Thankyou for the explination! If I could. I would +1
    – Daryl Gill
    Nov 21, 2012 at 18:15
  • @DarylGill Just register it as an accepted answer (the check mark) for future users who visit this thread. Nov 21, 2012 at 18:17
  • @FlorinStingaciu +1, I didn't expect this to require that much explanation :)
    – emartel
    Nov 21, 2012 at 18:35
1

register_shutdown_function registers a shutdown hook, which is a function to be executed when the script shuts down. It takes a callback function as parameter, which is the function to be executed.

I recommend that you check out the function's documentation.

Not the answer you're looking for? Browse other questions tagged or ask your own question.