Artem O.
Artem O.

Reputation: 3487

PHP singleton class lifetime hack

I have a very specific issue which I can't solve.

I have a PHP system which consist of a number of classes. Most of them are generic classes and are loaded by using autoload handler, and created in a global scope manually ( new operator ).

But I also have one main and very important singleton class, which also exists in a global scope and is created first. I want to make it live till the end. This class ( created first ) must be destroyed last.

This class is a error-processing class, and it have only two public methods which will be used to manage errors, catch exceptions, check exit, send reports, etc.

But, this class will destroy first as it was created first.

Is it possible to affect the class's lifetime and make it die after all other classes have died?

Thanks.

upd extended code samples:

each class defined in separated file

class longlive { // error processing class
    private function __construct() {}

    public static function initialize() {
        self::$instance = new longlive();
    }

    public function __destruct() {
        /// check for runtime session errors, send reports to administrators
    }

    public static function handler( $errno, $errstr, $errfile = '', $errline = '', $errcontext = array() ) {
        /// set_error_handler set this method
        /// process errors and store 
    }

    public static function checkExit() {
        /// register_shutdown_function will register this method
        /// will trigger on normal exit or if exception throwed
        /// show nice screen of death if got an uncoverable error
    }
}

class some_wrapper {
    public function __construct() {}
    public function __destruct() {}
}

class core {
    private function __construct() {
        $this->wrapper = new some_wrapper();
    }

    public static function initialize() {
        self::$core = new core();
    }
}

script body:

include_once( 'path/to/longlive.php' );
longlive::initialize();

include_once( 'path/to/core.php' );
core::initialize();

Upvotes: 1

Views: 1381

Answers (1)

Vyktor
Vyktor

Reputation: 21007

If you were using Zend Framework you could do this:

Yours::initialize();
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()
            ->run();
unset( $application);
Yours::destroy();

If you're using your own code your only option is probably:

Yours::initialize();
runApplication(); // This will contain all other objects in local scope and they
                  // will be destroyed before yours
Yours::destroy();

Or hack shutdown handler with code like this:

foreach( $GLOBALS as $key => $val){
  unset( $GLOBALS[ $key]);
}

Yours::destroy();

Upvotes: 1

Related Questions