Home >Backend Development >PHP Tutorial >Make good use of the new features of PHP5.3 to implement singleton mode_PHP tutorial

Make good use of the new features of PHP5.3 to implement singleton mode_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:41:34958browse

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.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/678027.htmlTechArticleIt 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 this class...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn