Articles

The month of PHP functions : script extinction

  • Ecrit par Julien Pauli
  • jeudi 26 avril 2007
Image pour le titre du contenu

Ce document est aussi disponible en français fr 


register_shutdown_function() registers a function to be executed during script shutdown. This will be useful to clean up the environnement before PHP actually destroy all resources. Using create_function() , we may also execute several functions at the same time.


Example 1 - Closing several files at the same time with create_function() :

<?php
register_shutdown_function(create_function('', 'fclose($file1); fclose($file2); return true;'));
?><strong>
</strong>

Example 2 - Removing a temporary file

<?php
function cleanup() {
  global $tmpfile;
 
  if ($tmpfile)
    @unlink ($tmpfile);
}
 
function my_tempnam() {
  global $tmpfile;
 
  if (!$tmpfile) {
    $tmpfile = tempnam("/tmp", "tmpfile");
    register_shutdown_function ("cleanup");
  }
  return $tmpfile;
}
?>

Exemple 3 - Fabrique d'objet avec enregistrement autommatique d'une méthode de fermeture :

<?php
class MyClass
{
    static private $callbackClassName = null;
 
    static public function init( $callbackClassName )
    {
        if ( !class_exists( $callbackClassName ) )
        {
            throw new Exception( $callbackClassName.' n\existe pas');
        }
    self::$callbackClassName = $callbackClassName;
        register_shutdown_function( array( __CLASS__, 'shutdownCallbackHandler' ) );
    }
 
    static public function reset()  { /*...*/  }
 
    static public function cleanExit()  { /*...*/ }
 
    static public function shutdownCallbackHandler()
    {
            call_user_func( array( self::$callbackClassName, 'Exit' ) ); 
    // calling the exit methode using init()
    }
}
?><strong>
</strong>

A mémoriser

  • Even if connexion with the browser is closed, or if the script is time outing, shutdown functions will be called.
  • Several functions may be registered, and they will be called in the order or registration.
  • Shutdown functions are called after objects desctructions, and before PHP stops.
< Précédent   Suivant >

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter