julio
julio

Reputation: 6728

php singleton object not created

I'm trying to learn about OOP, and create a singleton to return a settings object within a PHP script. For some reason, the instance never seems to get set.

I'm echoing a message getting settings anytime the singleton goes through its construct (it's silent if it just returns the existing instance).

When this is called from within a script, I'm getting dozens of these getting settings messages, one for each time I call mySettings::getSettings()-- $instance doesn't seem to be created, even when I try to dump it immediately after it is created.

Can anyone point out where I'm going wrong?

Here's the code:

class mySettings {
    private $settings;
    private static $instance;

    private function __construct(){
        $configfile = "myconfig.ini";
        if(!$this->settings = parse_ini_file( $configfile )){
            die('CONFIG NOT FOUND/PARSED');
        }
    }

    public static function getSettings(){
        if ( !self::$instance ){
            echo "getting settings-- no instance found!";
            self::$instance = new mySettings();
            var_dump(self::$instance); // <-- dumps nothing
        }
        return self::$instance;
    }

    public function setParam( $key, $value ){
        $this->settings[$key] = $value;
    }

    public function getParam( $key ){
        return $this->settings[$key];
    }
}

Upvotes: 1

Views: 185

Answers (2)

Bob Fanger
Bob Fanger

Reputation: 29897

Does: // <-- dumps nothing mean you see a "NULL" being rendered or nothing at all?

Maybe you've got some output buffering that hides the var_dump() output.

Upvotes: 0

ilanco
ilanco

Reputation: 9957

Your approach to creating a singleton looks correct.

Try with an empty constructor, there might be an issue with that die() statement there.

Upvotes: 1

Related Questions