標籤:http os io 資料 ar 2014 問題 cti
、
<?php//要解決的問題 在一個方法中多次調用類 //多次調用父類相同的類class Pdoo {public function __construct(){}//這是個資料庫的類function select($name) {echo "正宗" . $name;}}class Conn {static $db;private function __construct() {}private function __clone() {}//返回的的是資料庫的串連 而非Base類public static function getInstance() {if (self::$db == null) {self::$db = new Pdoo ();}return self::$db;}//這個方法是無效的function select($name) {echo $name;}}class Db {static $db;static $instanceInternalCache;private function __construct() {//初始話 跟串連資料庫沒有任何關係的}private function __clone() {}//不能在這裡執行個體化 否則資料庫連接就無效了public static function getDb() {}//這裡解決 在同一個方法中多次調用A不會被多次執行個體化//解決不了多個衍生類別被執行個體化 也就是有多少衍生類別 資料庫就要串連多少次public static function getInstance($model) {if (self::$instanceInternalCache [$model] == NULL) {self::$instanceInternalCache [$model] = new $model ();}return self::$instanceInternalCache [$model];}function select($name) {Conn::getInstance ()->select ( $name );}}class A extends Db {function s($name) {$this->select($name);}public static function instance() {return parent::getInstance ( __CLASS__ );}}class B extends Db {function s($name) {$this->select($name);}public static function instance() {return parent::getInstance ( __CLASS__ );}}class Main {public function t() {A::instance ()->select ( "1" );A::instance ()->select ( "11" );B::instance ()->select ( "2" );}}$t = new Main ();$t->t ();