Singletons

From: Date: Mon, 20 Oct 2008 17:07:59 +0000
Subject: Singletons
Groups: php.general 
Request: Send a blank email to php-general+get-282133@lists.php.net to get a copy of this message
Ok, so why isn't this working as (I, at the very least) expected? class singleTon { private static $thisObj = NULL; private $thisProp = NULL; public function __construct() { echo 'singleTon::__construct()<br>'; if( !is_null( singleTon::$thisObj )) { echo '$thisObj already set. returning it...<br>'; return singleTon::$thisObj; } singleTon::$thisObj = $this; } public static function singleton() { echo 'singleTon::singleton()<br>'; if( is_null( singleTon::$thisObj )) { $retval = new singleTon(); } return singleTon::$thisObj; } public function setThisProp( $sVal ) { $this->thisProp = $sVal; } public function getThisProp() { return $this->thisProp; } } $one = singleTon::singleton(); $one->setThisProp( 'Joe' ); echo '$one->getThisProp();: [' . $one->getThisProp() . ']<br>'; echo '$one: [<pre>' . var_export( $one, TRUE ) . '</pre>]<br>'; $two = new singleTon(); echo '$two->getThisProp();: [' . $two->getThisProp() . ']<br>'; $two->setThisProp( 'Bob' ); echo '$two: [<pre>' . var_export( $two, TRUE ) . '</pre>]<br>'; echo '$one->getThisProp();: [' . $one->getThisProp() . ']<br>'; echo '$two->getThisProp();: [' . $two->getThisProp() . ']<br>'; echo '$one->getThisProp();: [' . $one->getThisProp() . ']<br>'; I would have thought that both $one and $two would be referencing the same object but they aren't. Apart from making the constructor private, is there any way I can ensure that there is ever only one instance of an object? thnx, Christoph

« previous php.general (#282133) next »