php 设计模式
php 设计模式
1: php 工厂设计模式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?php /** php工厂模式 工厂模式:该工厂只负责生产和创建对象,工厂方法的参数是 你要生成对象对应的名称。 如下示例,在当前目录创建 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(); ?>
2:php 单例设计模式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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错误; ?>
3:json 数据处理
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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); ?>
4:数据库连接设计
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?php class 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'); ?>