PHP Object Lifecycle

Published 1 month ago by tuxaanand

Hi All,

Is there a way to reuse Objects across requests i.e. across multiple RINIT & RSHUTDOWN?

Thanks, Aanand

bobbybouwmann

It's sounds like you need the singleton pattern!

Example: https://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5

tuxaanand

Hi Bobby,

Yes a singleton object to have an application context as shown below. But the constructor and the destruct function/methods get invoked for every request.

Is there a way to hold objects from getting garbage collected/destroyed between requests?

<?php

final class ApplicationContext
{
    private static $inst = null;
    
    public static function Instance()
    {
        if ($inst === null) {
            $inst = new ApplicationContext();
        }
        return $inst;
    }

    private function __construct()
    {
        echo "constructor <br/>";
    }

    public function __destruct() {
        echo "destroyed <br/>";
    }

}

ApplicationContext::Instance();

Thanks, Aanand

martinbean

@tuxaanand It would be good to know what problem it is you’re trying to solve. Trying to persist a PHP object across HTTP requests sounds… odd.

Please sign in or create an account to participate in this conversation.