PDA

View Full Version : [TUT] Using the Singleton Pattern



0x00
23-07-2011, 02:16 AM
Using the singleton pattern is drop-dead easy. I'll guild you through it...

Make a PHP file and define a class and static function and variable... Like this...


<?php
class singleton
{
# static so we don't need to make an instance of this
private static $instances = array();

# static so we don't need to make an instance of this
public static function instance($class)
{
}
}


Now, to put our business in the function:


class singleton
{
# static so we don't need to make an instance of this
private static $instances = array();

# static so we don't need to make an instance of this
public static function instance($class)
{
if(!isset(self::$instances[$class])) # does the class already exist?
self::$instances[$class] = new $class; # new class

return self::$instances[$class]; # return it!
}
}


How easy was THAT!?

What are the advantages of using this?
Well, it limits the number of instances of the class there is. Like if you have a query on your __construct function, then you'd need singleton so that PHP doesn't 'lag' and make more instances than there should be, therefore running the query too much.
#-#-#-#-#-#-#-#-#-#-#-

I hope you guys still aren't using globals! (berk RadiPanel)

Want to hide these adverts? Register an account for free!