1

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];
    }
}
4
  • 1
    Tested your code. Works. Commented May 10, 2012 at 17:19
  • @julio, webbiedave and i both got it to work right. perhaps something elsewhere (outside of that class) is going wrong. Commented May 10, 2012 at 17:22
  • thanks for the help guys. I'll update with the other functions that could be the issue and take a look at those. Commented May 10, 2012 at 17:25
  • Code works completely. I think the error is somewhere else. Could you show your real code? Commented May 10, 2012 at 17:38

2 Answers 2

1

Your approach to creating a singleton looks correct.

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

Sign up to request clarification or add additional context in comments.

2 Comments

if it were dying, it would say the die message, wouldn't it?
@Kristian-- yes, in fact the die statement is operational, if I give a bad path or an empty value for the config file, it will die. Also, if I dump the value returned by $var = mySettings::getSettings() elsewhere, it does have the expected value.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.