Jump to content
Larry Ullman's Book Forums

Recommended Posts

I tried to force an error by assigning the variable $CONFIG to the class Config but for some reason, the output didn't generate an error, it simply didn't display anything.

 

 

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head> 
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
 
</head>
<body>
<h2>Using a Singleton Config Object</h2>
<?php
require('Chapter7_Config.php');
//$CONFIG = Config::getInstance();
$CONFIG = new Config();
$CONFIG->set('live', 'true');
echo '<p>$CONFIG["live"]: ' . $CONFIG->get("live") . '</p>';
$TEST = Config::getInstance();
echo "<p>$TEST['live']: " . $TEST->get('live') . "</p>";
unset($CONFIG, $TEST);
?>
</body>
</html>
 
class Config {
    
    // Store a single instance of this class:
    static private $_instance = NULL;
 
    // Store settings:
    private $_settings = array();
    
    // Private methods cannot be called: 
    private function __construct() {}
    private function __clone() {}
    
    // Method for returning the instance:
    static function getInstance() {
        if (self::$_instance == NULL) {
            self::$_instance = new Config();
        }
        return self::$_instance;
    }
    
    // Method for defining a setting settings:
    function set($index, $value) {
        $this->_settings[$index] = $value;
    }
    
    // Method for retrieving a setting:
    function get($index) {
        return $this->_settings[$index];
    }
    
} // End of Config class definition.
 
Also, I was just wondering if this design pattern would be typical of web instances or database instances being distributed over multiple servers.
Link to comment
Share on other sites

I'm not quite sure I follow. You're saying that if you had this line:

 

$CONFIG = Config::getInstance();
without this line:
$CONFIG = new Config();
nothing happened at all?
 
As for your other question, what do you mean by a "web instance" or a "database instance"?
Link to comment
Share on other sites

I was trying to exploit the restrictive behavior of the Singleton pattern by attempting to create an object using a standard call to the __construct method: $CONFIG = new Config(). I was expecting to receive an error but nothing happened. No error and no output.

 

Web site instances are iterations of a web site running on multiple servers. Typically, the instances would be load balanced to attenuate traffic and maintain accessibility. 

Link to comment
Share on other sites

 Share

×
×
  • Create New...