單例模式是開發中常用的設計模式,利用 PHP5 物件導向特性可輕易建構單例應用。以下為幾種實作方式:
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();
在 getInstance 方法中回傳唯一類別實例。
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();
稍加修改即可產生通用方法,放入任何想用單例的類別中即可使用。