note 40783 added to keyword.paamayim-nekudotayim

From: Date: Sun, 14 Mar 2004 19:28:36 +0000
Subject: note 40783 added to keyword.paamayim-nekudotayim
Groups: php.notes 
Request: Send a blank email to php-notes+get-66831@lists.php.net to get a copy of this message
Using a class function is a good way to write a Singleton pattern in php 4 using a static variable. The sample code below shows the pattern in action : <? class Singleton { var $_info = null; function Singleton() { $this->_info = 'Original value'; } function getInfo() { return $this->_info; } function setInfo($info) { $this->_info = $info; } function &getInstance() { static $instance = null; if (is_null($instance)) { $instance = new Singleton(); } return $instance; } } $a = & Singleton::getInstance(); $b = & Singleton::getInstance(); $a->setInfo('Hi, my name is A'); echo $b->getInfo(); ?> I have seen some Singleton pattern implementations that were using an external function to instanciate the object, but I don't think it is the best way to implement the pattern. You may want to force the getInstance() function to be called in a static way with the :: operator by testing if $this is set and raising an error or returning a null value (depending on your design). ---- Manual Page -- http://www.php.net/manual/en/keyword.paamayim-nekudotayim.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40783 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40783&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40783&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#66831) next »