Today I was thinking about using PHP to use singleton, and I saw a relatively comprehensive summary - several implementations of singleton mode. The implementation of PHP5 summarized in it:
PLAIN TEXTPHP:
class MyClass
{
private static $instance;
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
}
This code is not very comfortable to use, because it is generally inherited from MyClass, and $c = __CLASS__; always obtains the class name of the base class, which is not available. We can only consider finding other implementation methods.
Then I started to look at the singleton implemented in the function method in the article. The implementation was very good. The disadvantage is that the class cannot be instantiated with parameters. Here is my version:
PLAIN TEXTPHP:
function getObj() {
static $obj = array();
$args = func_get_args();
if(empty($args))
return null;
$clazz = $args[0];
if(!is_object($obj[$clazz])) {
$cnt = count($args);
if($cnt> 1) {
for($i = 1, $s = ''; $i <$cnt; $i++)
$s[] = '$args[' . $i . ']';
eval('$obj[$clazz] = new $clazz(' . join(',', $s) . ');');
} else {
$obj[$clazz] = new $clazz;
}
}
return $obj[$clazz];
}
It can be easily called under php5:
PLAIN TEXTPHP:
getObj('MyClass', $param1, $param2)->myMethod();
Previous naive version:
Simple implementation of monad mode (SINGLETON)