1

I have a class which reads some settings from an XML file with simplexml. If I build it in the singleton style and save those settings in a publicly accessible array, does that mean it would effectively retrieve the file only once?

Basically, in a simplified form, this:

class myClass {
    public $_requestConfiguration;
    public $_conditions;
    public $_requestSets;

    private static $_instance;

    private function __construct() {
        $configFile = simplexml_load_file(APPLICATION_PATH.'/configs/chapter_requests.xml');
        $this->_requestConfiguration = $configFile->requests->request;
        $this->_conditions = $configFile->conditions;
        $this->_requestSets = $configFile->request_sets;
    }

    public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}
Swader
  • 11,387
  • 14
  • 50
  • 84
  • 1
    the constructor can only be invoked once (when there is no `self::$instance`) and you parsing happens in the constructor.. So, yes. – prodigitalson Jun 07 '11 at 08:03

2 Answers2

3

You will indeed have only one instance and the XML file will only be read once for the execution of the script.

When the script is done executing everything will be removed from memory and on the next run your 'singleton' will start reading the XML again because the static instance is no longer stored in memory.

I've somewhat asked the same question over here.

Community
  • 1
  • 1
Kevin
  • 5,626
  • 3
  • 28
  • 41
  • Yes, this I know, I meant during the current script. Some of my scripts require up to 50-60 round trips back to the XML data in order to fetch more conditional details, and I just wanted to make sure I wouldn't be reloading the file at every instance call. Reloading it after the script finished is just fine. – Swader Jun 07 '11 at 08:22
0

Yes.

Adding comical banter to reach minimum of 30 characters.

John Hargrove
  • 701
  • 6
  • 23