Re: Singletons
| From: | Nathan Rixham | Date: | Mon, 20 Oct 2008 17:21:15 +0000 |
| Subject: | Re: Singletons | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-282136@lists.php.net to get a copy of this message | ||
Christoph Boget wrote:
Ok, so why isn't this working as (I, at the very least) expected? class singleTon {you can't return from a constructor; thus always use the static singleton method() i.e.: $two = singleTon::singleton(); -- nathan ( nathan@kraya.co.uk ) { Senior Web Developer php + java + flex + xmpp + xml + ecmascript web development edinburgh | http://kraya.co.uk/ }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