当前位置:Gxlcms > PHP教程 > PHP链式操作的思想详解

PHP链式操作的思想详解

时间:2021-07-01 10:21:17 帮助过:31人阅读

本文主要介绍了PHP实现链式操作的核心思想。本文着重讲解它的核心思想,比较直观明了。希望对大家有所帮助。

PHP 链式操作的实现

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

在 Common 下创建 Database.php。

链式操作最核心的地方在于:在方法的最后 return $this;

Database.php:


<?php
namespace Common;

class Database{
  function where($where){
    return $this;  //链式方法最核心的地方在于:在每一个方法之后 return $this
  }
  function order($order){
    return $this;
  }
  function limit($limit){
    return $this;
  }
}


index.php:


<?php
define('BASEDIR',__DIR__); //定义根目录常量
include BASEDIR.'/Common/Loader.php';
spl_autoload_register('\\Common\\Loader::autoload');

$db = new \Common\Database(); 

//传统的操作需要多行代码实现
//$db->where('id = 1');
//$db->where('name = 2');
//$db->order('id desc');
//$db->limit(10);

//使用链式操作,一行代码解决问题
$db->where('id = 1')->where('name = 2')->order('id desc')->limit(10);


在使用链式操作时,ide(netbeans 会给出自动提示):

相关推荐:

php 对象实例化单例方法详解

PHP 对象的存储与传输(序列化 serialize 对象)

PHP 对象克隆 clone 关键字与 __clone() 方法

以上就是PHP链式操作的思想详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行