Question

I have this simple singleton class:

public static function getInstance() {                
    if (!self::$_controller) {
        self::$_controller = new self();
    }

    return self::$_controller;
}

Using PHP 5.3, this code seems to work fine, but on PHP 5.2 it seems like the instance is not returned. I put in a simple debug message like so:

public static function getInstance() {                
    if (!self::$_controller) {
        self::$_controller = new self();
        echo "I seem to be working";
    }

    return self::$_controller;
}

But "I seem to be working" is never echoed out. What's going on here and how can I fix it?

Was it helpful?

Solution

The following is working at my end for PHP 5.3 and 5.2 both.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 0);

class SingleTon {
        private static $_controller = null;

        private function __construct() {
                // do something here or leave it blank.
        }

        public static function getInstance() {
                if (!self::$_controller) {
                        self::$_controller = new self();
                        echo "I seem to be working";
                }

                return self::$_controller;
        }
}

$obj = SingleTon::getInstance();
echo "\n";

?>

It displays "I seem to be working". Let me know if you need any further assistance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top