Singleton Pattern in PHP5

Written by Garry Lachman (Admin). Filed under PHP + mySQL. Tagged , , , , , , , , . Bookmark the Permalink. Post a Comment. Leave a Trackback URL.

Singleton is very basic design pattern.
If the instance is inited once than the class return the same instance.

Example of signleton in php5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?
Class SingletonExample {
  static private $instance;

  private function __construct() {
  }

  static function getInstance() {
    if(!Self::$instance) {
      Self::$instance = new SingletonExample();
    } else {
      return Self::$instance
    }
  }

  public function doHello() {
     return "Hello World";
   }
?>

Usage Example:

1
2
3
4
5
6
<?
include_once("singleton.class.php");

$single = SingletonExample::getInstance();
echo $single->doHello(); //return "Hello World"
?>
Share

3 Comments

  1. Posted March 4, 2010 at 3:17 pm | Permalink

    Congrats on your blog.

    Consider looking at this before you choose to use the Singleton pattern:

    http://moisadoru.wordpress.com/2010/03/02/static-call-versus-singleton-call-in-php/

  2. Posted March 10, 2010 at 10:08 pm | Permalink

    Don’t forget to read this before you go and implement a Singleton pattern:

    http://moisadoru.wordpress.com/2010/03/02/static-call-versus-singleton-call-in-php/

  3. admin
    Posted April 12, 2010 at 1:42 am | Permalink

    Thanks Jon ;)

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*