理解PHP链式调用

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

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

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

class Database
{
    public function where($where)
    {
         
    }
    public function order($order)
    {
         
    }
    public function limit($limit)
    {
         
    }
    
}
//代码调用
$db = new DatabaseDatabase();
$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 DatabaseDatabase();
$db->where('...')->order('...')->limit('...');

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

原文地址:https://www.cnblogs.com/ddddemo/p/5623472.html