Home > Backend Development > PHP Tutorial > Detailed explanation of the idea of ​​PHP chain operation

Detailed explanation of the idea of ​​PHP chain operation

*文
Release: 2023-03-18 15:50:01
Original
1485 people have browsed it

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

PHP 链式操作的实现

 $db->where()->limit()->order();
Copy after login

在 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;
  }
}
Copy after login


index.php:


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

$db = new \Common\Database(); 

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

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


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

 

相关推荐:

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

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

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

The above is the detailed content of Detailed explanation of the idea of ​​PHP chain operation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template