Archive for January 22, 2008

Singleton Pattern in PHP

Singleton design pattern is used to control the instantiation of a class to an Object. The singleton pattern is implemented by creating the class with a method that creates an instance if one does not exists and the constructor of the class is private.

We can implement this in PHP-5 as followings

<?php

class Singleton {

// object instance

private static $instance;

//constructor
private function __construct() {}

//clone
private function __clone() {}

//make instance
public static function getInstance() {

if (self::$instance === null) {//checking the previous instance

self::$instance = new self;

}

return self::$instance;

}

//the other methods of this class

public function doAction() {

}

}

?>

<?php

//usage

Singleton::getInstance()->doAction();

?>

In this example we can see that a static variable $instance is declared to hold the instance of the class. Also the constructor and clone method is private, this ensure the controlling of making the new object of that class.

After that we make a public function getInstance to make an instance of the class. This function return a new instance if no instance of the class is not exists, if exists this return that instance.

AND the uses is simple just use $class_name->getInstance() to make a new instance of the class.

Thanks

Comments (2)

Behavior isset, empty and casting of a variable as boolean in if statement

Suppose you want to check a variable is available or not. Then we can use the following

1. using isset:

if(!isset($var)){

//do something

} else{

//do something

}

2. Using empty:

if(!empty($var)){

//do something

} else{

//do something

}

3. Using the Implicit casting facility

if($var){

//do something

} else{

//do something

}

Now explanation and others

1. the isset function just check only if the variables is set(defined/declared) or not. If defined then return true else return flase. But this don’t check that the variable has a value or empty. So you should be careful to use this function. example:

isset($var);// this will return false

—————-

$var =  ‘test’;

isset($var);//this will return true

———-

$var = ”;

isset($var) //this will also return true

2. if u use empty then
Returns FALSE if $var has a non-empty and non-zero value.

The following things are considered to be empty:

“” (an empty string)
0 (0 as an integer)
“0″ (0 as a string)

and this is an opposite of (boolean)$var.

3.  Casting of the variable

if you use the casting then it will work as empty method but warning is generated when the variable is not set.

****As of PHP 5, objects with no properties are no longer considered empty

Leave a Comment