理解PHP链式调用

php链式操作:类似如下实现

$db->where()->limit()->order();

  •  不使用链式调用时的代码格式如下:
namespace Database;

class Database
{
    public function where($where)
    {
         
    }
    public function order($order)
    {
         
    }
    public function limit($limit)
    {
         
    }
    
}
//代码调用
$db = new Database\Database();
$db->where('...');
$db->order('...');
$db->limit('...');

 

  • 使用链式调用时的代码格式
<?php
namespace Database;

class Database
{
    public function where($where)
    {
        return $this;
    }
    public function order($order)
    {
        return $this;
    }
    public function limit($limit)
    {
        return $this;
    }
    
}
//代码调用
$db = new Database\Database();
$db->where('...')->order('...')->limit('...');

 

总结:链式调用核心部分,在每一个方法后return $this;那么$this是什么呢?是Database类的对象

 

posted @ 2016-06-28 15:01  DDDDemo  阅读(478)  评论(0)    收藏  举报