Singletons

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux