开发者

one class instance

is there a way to prevent the instance of the same class in a PHP script?

$user = new User();


$user2 = new User();  // I want to catch another instance of the user class and 开发者_如何学编程throw an exception

I have tried creating a static variable and manipulating it with a static function:

User::instance()

but that doesn't stop me from doing:

$user = new User();


Without changing object semantics, you could keep a static counter in the constructor. This is not a singleton, as it's not globally available, just only instantiatable once...

class Foo {
    private static $counter = 0;
    final public function __construct() {
        if (self::$counter) {
            throw new Exception('Cannot be instantiated more than once');
        }
        self::$counter++;
        // Rest of your constructor code goes here
    }
    // Rest of class
}


<?php
class Foo {
  static function instance() {
    static $inst = null;
    if ($inst === null) { $inst = new self; }
    return $inst;
  }
  private function __construct() { }
  private function __clone() { }
}


Here is code for a singleton in PHP.

http://www.developertutorials.com/tutorials/php/php-singleton-design-pattern-050729/page1.html


It's been a while since I've tried to do this, but have you tried making your __construct method protected or private?


I'm not sure about php syntax and language features, but you could have a static field in your class of type User that will keep an instance of your User object. And make the constructor throw an error. That way when you want an instance of your class you can call User.Instance and that will return the only existent instance. If you attempt to instantiate the object it will throw an error.

In C# it would look something like this. As I mentioned, I don't know the php syntax.

class User
{
  private static User instance = null;

  public User()
  {
      //throw exception
  }

  public static User Instance
  {
    get 
    {
       if(instance == null)
       {
          instance = new User();
       }
       return instance;
    }
  }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜