A: 

Ummmm.... singleton

Mark Baker
+2  A: 

That's a Singleton.

chrissr
+2  A: 

You're looking for a Singleton.

Check out this tutorial about implementing a singleton with php (as per your tag).

froadie
+2  A: 

singleton but i always ,always think twice before making use of it.

Srinivas Reddy Thatiparthy
+3  A: 

You really need to think about your specific situation. Here are some patterns to keep in mind when deciding what works in you need. Often, the Singleton can be used effectively with either a Service Locator or a Factory.

Singleton

Service Locator

Factories

grossvogel
+1  A: 

Here's an Singleton pattern example in PHP. Technically, it allows up to two instances to be created, but croaks in the constructor when an instance already exists:

<?php

class Singleton {

 static protected $_singleton = null;

 function __construct() {
  if (!is_null(self::$_singleton))
   throw new Exception("Singleton can be instantiated only once!");
  self::$_singleton= $this;  
 }

 static public function get() {
   if (is_null(self::$_singleton))
    new Singleton();
   return self::$_singleton;
 }

}

$s = new Singleton();
var_dump($s);
$s2 = Singleton::get();
var_dump($s2);  // $s and $s2 are the same instance.
$s3 = new Singleton();  // exception thrown
var_dump($s3);  

You'll also want to take a look at __clone depending on how tightly you need to control the instance invocations.

pygorex1
Why not make the constructor private?
mmattax
private constructors? Didn't know PHP supported them. NICE
pygorex1
A: 

You're looking for the Singleton pattern.


class Foo {

    private static $instance = null;

    private function __construct() { }

    public static function instance() {

        if(is_null(self::$instance))
            self::$instance = new Foo;

        return self::$instance;
    }

    public function bar() {
        ...
    }
}

$foo = Foo::instance();
$foo->bar();

mmattax