PHP Singleton Method


 

PHP Singleton Method

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.

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();

?>

 

Ads