Home >Backend Development >PHP Tutorial >Make good use of the new features of PHP5.3 to implement singleton mode_PHP tutorial
It can also be implemented before 5.3, but the code is more cumbersome, as follows:
class MOrder extends SModel{
protected static $handle; //single case handle
private function __construct(){
//something
}
/**
* Get the method of this type of singleton, public
*
* @return MOrder
*/
public static function instance() {
if(self::$handle){
return self::$handle;
}
$class = __CLASS__;
self::$handle = new $class();
return self::$handle;
}
//otherthing
}
5.3 Add delayed static binding (this word is really awkward)
The code is implemented as follows
class SModel {
/**
* Get the singleton handle and return the instance object of the specific model class
*/
protected static function instance() {
if(static::$handle){
return static::$handle;
}
$class = get_called_class();
static::$handle = new $class();
return static::$handle;
}
//Parent class something
}
class MGoods extends SModel{
/**
* Get the method of this type of singleton, public
* @return MGoods
*/
public static function instance(){
return parent::instance();
}
protected static $handle; //single case handle
protected function __construct(){
//something
}
//otherthing
}
Through modification, part of the implementation code of the subclass is reduced and implemented by the parent class
To be honest, it’s still very troublesome. It would be nice if PHP implemented singleton itself.