Single-piece mode is a design pattern that we often use in development, using PHP5 object-oriented features, we can easily build the application of single piece mode, the following is a single piece mode in PHP several implementation methods:
class Stat{
static $instance = NULL;
static function getInstance(){
if(self::$instance == NULL){
self::$instance = new Stat();
}
return self::$instance;
}
private function __construct(){
}
private function __clone(){
}
function sayHi(){
return "The Class is saying hi to u ";
}
}
echo Stat::getInstance()->sayHi();
This is the most common way to return a unique class instance in a GetInstance method.
With a little modification of the example here, you can produce a generic method, just call any class that you want to use in a single piece.
class Teacher{
function sayHi(){
return "The teacher smiling and said 'Hello '";
}
static function getInstance(){
static $instance;
if(!isset($instance)){
$c = __CLASS__;
$instance = new $c;
}
return $instance;
}
}
echo Teacher::getInstance()->sayHi();