tags:

views:

58

answers:

4

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();
+1  A: 

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

Charles
+1  A: 
<?php
class Foo {
  static function instance() {
    static $inst = null;
    if ($inst === null) { $inst = new self; }
    return $inst;
  }
  private function __construct() { }
  private function __clone() { }
}
Ollie Saunders
is this the same as doing it the singleton way?
Ygam
That is a singleton.
Ollie Saunders
I just fixed an error btw.
Ollie Saunders
A: 

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;
    }
  }

}
Mircea Grelus