Home » Php » Register static class method as shutdown function in PHP

Register static class method as shutdown function in PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

In PHP is it possible to register a shutdown function (with register_shutdown_function()) which is a static method implemented in a class? I mean something like this:

//index.php
require_once("modules/Analyzer/Analyzer.php");
register_shutdown_function("Analyzer::log_shutdown");

//Analyzer.php
class Analyzer {
   ...

   public static function log_shutdown(){
      // do some awesome stuff
      Analyzer::screenshot();
   }
}
How to&Answers:

The first argument passed to register_shutdown_function is of the type callable. A callable static method looks like this:

register_shutdown_function(array('Analyzer', 'log_shutdown')); 

As of PHP 5.2.3 it may also look exactly like what you originally posted

Answer:

Can use an anonymous function:

register_shutdown_function(function(){
    Analyzer::log_shutdown();
});

also, in analyzer you can use a call to the same class like this:

class Analyzer{
    public static function log_shutdown(){
        self::screenshot();
    }
}

Answer:

Eventually via namespace:

register_shutdown_function(function(){
    \app\modules\Analyzer\Analyzer::log_shutdown();
});

or

register_shutdown_function(['\app\modules\Analyzer\Analyzer', 'log_shutdown']);
register_shutdown_function(["\app\modules\Analyzer\Analyzer", "log_shutdown"]);