当前位置:首页 > PHP教程 > php应用 > 列表

php链式操作的实现

发布:smiling 来源: PHP粉丝网  添加日期:2022-06-04 09:17:48 浏览: 评论:0 

php链式操作的关键是在做完操作后要return $this;

一、不使用__call方法实现链式操作

  1.  
  2. class Sql{ 
  3.  
  4.     private $sql=array("from"=>"", 
  5.  
  6.             "where"=>"", 
  7.  
  8.             "order"=>"", 
  9.  
  10.             "limit"=>""); 
  11.  
  12.  
  13.  
  14.     public function from($tableName) { 
  15.  
  16.         $this->sql["from"]="FROM ".$tableName; 
  17.  
  18.         return $this; 
  19.  
  20.     } 
  21.  
  22.  
  23.  
  24.     public function where($_where='1=1') { 
  25.  
  26.         $this->sql["where"]="WHERE ".$_where; 
  27.  
  28.         return $this; 
  29.  
  30.     } 
  31.  
  32.  
  33.  
  34.     public function order($_order='id DESC') { 
  35.  
  36.         $this->sql["order"]="ORDER BY ".$_order; 
  37.  
  38.         return $this; 
  39.  
  40.     } 
  41.  
  42.  
  43.  
  44.     public function limit($_limit='30') { 
  45.  
  46.         $this->sql["limit"]="LIMIT 0,".$_limit; 
  47.  
  48.         return $this; 
  49.  
  50.     } 
  51.  
  52.     public function select($_select='*') { 
  53.  
  54.         return "SELECT ".$_select." ".(implode(" ",$this->sql)); 
  55.  
  56.     } 
  57.  
  58. } 
  59.  
  60.  
  61.  
  62. $sql =new Sql(); 
  63.  
  64.  
  65.  
  66. echo $sql->from("testTable")->where("id=1")->order("id DESC")->limit(10)->select(); 
  67.  
  68. //输出 SELECT * FROM testTable WHERE id=1 ORDER BY id DESC LIMIT 0,10 
  69.  
  70. ?> 

二、使用__call方法实现链式操作

__call()在对象调用一个不可访问的方法时会被触发,所以可以实现类的动态方法的创建,实现php的方法重载功能,但它其实是一个语法糖(__construct()方法也是)。

  1.  
  2. class String 
  3.  
  4. { 
  5.  
  6.     public $value; 
  7.  
  8.  
  9.  
  10.     public function __construct($str=null) 
  11.  
  12.     { 
  13.  
  14.         $this->value = $str; 
  15.  
  16.     } 
  17.  
  18.  
  19.  
  20.     public function __call($name, $args) 
  21.  
  22.     { 
  23.  
  24.         $this->value = call_user_func($name, $this->value, $args[0]); 
  25.  
  26.         return $this; 
  27.  
  28.     } 
  29.  
  30.  
  31.  
  32.     public function strlen() 
  33.  
  34.     { 
  35.  
  36.         return strlen($this->value); 
  37.  
  38.     } 
  39.  
  40. } 
  41.  
  42. $str = new String('01389'); 
  43.  
  44. echo $str->trim('0')->strlen(); 
  45.  
  46. // 输出结果为 4;trim('0')后$str为"1389" 
  47.  
  48. ?>

Tags: php链式操作

分享到: