The following are two singleton pattern implementations in Java and PHP respectively. Listing both of them here can clearly show the difference between Java and PHP static variables.
Java Singleton pattern
/** * @author Yiyu Jia */ public class DBConnectionFactory { // static means there will be only one instance in one JVM. private static DBConnectionFactory m_connFactory = new DBConnectionFactory(); // private means this class can not be created by "new" operator outside it. private DBConnectionFactory() { //connManagerList = new ConcurrentHashMap(); } public static DBConnectionFactory getInstance() { return m_connFactory; } }
To have better understand about Java memory management, singleton pattern, we can refer to this article and links inside it.
PHP singleton pattern
/** * @author Yiyu Jia */ class JiaLog { private static $_instance; private $logger; // declaring constructor to be private function. private function __construct() { $writer = new Zend_Log_Writer_Stream('path/to/logfile'); $this->logger = new Zend_Log($writer); } //public static function is the way allowed to get instance public static function getJiaLog() { if (!isset(self::$_instance)) { $c = __CLASS__; self::$_instance = new $c; } return self::$_instance; } public function info($str) { $this->logger->log($str, Zend_Log::INFO); } // Prevent users to clone the instance public function __clone() { trigger_error('Clone is not allowed.', E_USER_ERROR); } }
No comments:
Post a Comment