This article mainly introduces the core idea of PHP implementing chain operation. This article focuses on explaining its core idea, which is more intuitive. Friends in need can refer to it
Implementation of PHP chain operation
The code is as follows:
$db->where()->limit()->order();
Create Database.php under Common.
The core of the chain operation is: return $this;
at the end of the methodDatabase.php:
?
2 3
4
|
namespace Common;<🎜> <🎜> <🎜> <🎜>class Database{<🎜> <🎜>function where($where){<🎜> <🎜>return $this; //The core of the chain method is: return $this<🎜> after each method <🎜>}<🎜> <🎜>function order($order){<🎜> <🎜>return $this;<🎜> <🎜>}<🎜> <🎜>function limit($limit){<🎜> <🎜>return $this;<🎜> <🎜>}<🎜> <🎜>}<🎜> <🎜> |
<🎜>1<🎜> <🎜>2<🎜> <🎜>3<🎜> <🎜>4<🎜> <🎜>5<🎜> <🎜>6<🎜> <🎜>7<🎜> <🎜>8<🎜> <🎜>9<🎜> <🎜>10<🎜> <🎜>11<🎜> <🎜>12<🎜> <🎜>13<🎜> <🎜>14<🎜> <🎜>15<🎜> | <🎜> <🎜> <🎜>define('BASEDIR',__DIR__); //Define root directory constants<🎜> <🎜>include BASEDIR.'/Common/Loader.php';<🎜> <🎜>spl_autoload_register('\Common\Loader::autoload');<🎜> <🎜> <🎜> <🎜>$db = new CommonDatabase();<🎜> <🎜> <🎜> <🎜>//Traditional operations require multiple lines of code to implement<🎜> <🎜>//$db->where('id = 1'); //$db->where('name = 2'); //$db->order('id desc'); //$db->limit(10); //Use chain operations to solve the problem with one line of code $db->where('id = 1')->where('name = 2')->order('id desc')->limit(10); |