Re: Singletons

From: Date: Mon, 20 Oct 2008 17:18:11 +0000
Subject: Re: Singletons
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-282135@lists.php.net to get a copy of this message
On Mon, Oct 20, 2008 at 1:07 PM, Christoph Boget <christoph.boget@gmail.com> wrote: > 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 > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, visit: http://www.php.net/unsub.php > > Look at http://us3.php.net/manual/en/language.oop5.patterns.php for a working singleton example.

« previous php.general (#282135) next »