Share on Google+Share on Google+

PHP Singleton Method

Advertisement
In the current php tutorial we will study about singleton pattern of PHP, which is another type of designing pattern. Examples will help you understand in better way.

PHP Singleton Method:

Many application resources are exclusive like database, in that case the class should have a single object. The connection to a database is exclusive.

The singleton pattern is exactly the same, it uses for creating single object.

To get an instance of the singleton pattern we must have an accessor method in our program that will return an instance of the class but it will not allow to instantiate more than one instance at a time. In programming example we will create an object manually,

PHP Singleton Pattern Example:

<?php

final class single

{

protected static $_var;

private function __construct()

{ }

private function __clone()

{ }

public static function createObject()

{

if( self::$_var === NULL ) {

self::$_var = new self();

}

return self::$_var;

}

}}

$obj = Singleton::reateObject();

?>

 

Advertisements

Posted on: February 23, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.