標籤:style class blog code http tar
php 設計模式
1: php 工廠設計模式
<?php/** php原廠模式 原廠模式:該工廠只負責生產和建立對象,Factory 方法的參數是 你要產生對象對應的名稱。 如下樣本,在目前的目錄建立 Drive目錄, 然後分別建立類檔案 A.php,B.php 然後建立工廠類 Factory*///工廠類 class Factory{ public static function fac($type) { if(include_once ‘Drive/‘.$type.‘.php‘) { //echo ‘the className is:‘.$type.‘</br>‘; return new $type; } else { echo ‘driver not found‘; throw new Exception(‘Driver not found‘); } }}//使用工廠$a = Factory::fac(‘A‘);$a->method();$b = Factory::fac(‘B‘);$b->method();?>View Code
2:php 單例設計模式
<?php/** 單例設計模式-php Singleton 用於一個類產生一個唯一的對象,比如常用的是資料庫連接*/class Single{ //儲存類執行個體在此屬性中 private static $instance; //構造方法聲明為 private,防止直接建立對象 private function __construct() { echo ‘this is singleton!</br>‘; echo ‘please do not create by yourself!</br>‘; } //單例方法 public static function singleton() { if(!isset(self::$instance)) { $theClass = __CLASS__; self::$instance = new $theClass; } return self::$instance; } //單例中的普通方法 public function hello() { echo ‘hello everyone! I am singleton </br>‘; } //阻止使用者複製對象執行個體 public function __clone() { trigger_error(‘do not clone the singleton.‘,E_USER_ERROR); }}//$test = new Single(); //錯誤調用//單例的正確使用方式;$sing = Single::singleton();$sing-> hello();//clone測試//$test = clone $sing; //會收到,上面的 clone錯誤;?>View Code
3:json 資料處理
<?php header(‘Content-type: text/json‘); header(‘Content-type: application/json;charset=UTF-8‘); $arr = array(‘name‘=>‘jkk‘,‘age‘=>22,‘sex‘=>‘man‘,‘phone‘=>1321058559); echo json_encode($arr);?>
View Code
4:資料庫連接設計
<?phpclass Connection{ protected $link; private $server,$user_name,$password,$db; public function __construct($server,$user_name,$password,$db) { $this->server = $server; $this->user_name = $user_name; $this->password = $password; $this->db = $db; $this->connect(); } private function connect() { //這裡面初始為 $this->link 為 資料庫連接; echo "<hr>"; echo $this->server.‘</br>‘; echo $this->user_name.‘</br>‘; echo $this->password.‘</br>‘; echo $this->db.‘</br>‘; } }$con = new Connection(‘ubuntuServer14‘,‘test‘,‘test‘,‘db‘);?>View Code