php函数连续调用/链式调用方法详解与案例分析
Song •
1313 次浏览 •
0个评论 •
2021年07月23日
在我们使用PHP过程中可能看到连续调用/链式调用如Laravel
模型:
Mode::find()->where()->orderBy()->limit();
链式调用,重点在于,返回$this
指针,方便调用后者函数return $this
。
平常我们使用的类方法过程中,
$model = new BaseObject();
$model->where();
$model->limit();
当where
方法中最后返回$this
的时候我们就可以使用
$model->where()->limit();
代码如下:
<?php
class BaseObject
{
public $where;
public $limit;
function where($condition)
{
$this->where = $condition;
}
function limit($limit)
{
$this->limit = $limit;
}
}
$model = new BaseObject();
$model->where(['id' => 1]);
$model->limit(10);
var_dump($model);
结果为:
object(app\controllers\BaseObject)#1 (2) {
["where"]=> array(1) {
["id"]=> int(1)
}
["limit"]=>
int(10)
}
链式调用:
<?php
class BaseObject
{
public $where;
public $limit;
function where($condition)
{
$this->where = $condition;
return $this;
}
function limit($limit)
{
$this->limit = $limit;
return $this;
}
}
$model = new BaseObject();
$model->where(['id' => 1])->limit(10);
var_dump($model);
结果为:
object(BaseObject)#1 (2) {
["where"]=> array(1) {
["id"]=>int(1)
}
["limit"]=>int(10)
}
同时我们也可以结合使用魔法函数__call结合call_user_func来实现
<?php
class StringHelper
{
private $value;
function __construct($value)
{
$this->value = $value;
}
function __call($function, $args){
$this->value = call_user_func($function, $this->value, $args[0]);
return $this;
}
function strlen() {
return strlen($this->value);
}
}
$str = new StringHelper(" sd f 0");
echo $str->trim('0')->strlen();
-
laravel中distinct()的使用方法与去重 2017-09-11
-
Laravel将view缓存为静态html,laravel页面静态缓存 2021-10-09
-
[ laravel爬虫实战--基础篇 ] guzzle描述与安装 2017-11-01
-
[ 配置教程 ] 在ubuntu16.04中部署LNMP环境(php7+maridb且开启maridb远程以及nginx多域名访问 )并配置laravel环境 2017-07-18
-
oppo手机默认浏览器urlscheme 2025-02-13
热门文章
-
oppo手机默认浏览器urlscheme 2025-02-13
-
mysql如何给运营人员添加只有查询权限的账号 2024-12-02
-
Mac 安装mysql并且配置密码 2024-11-20
-
阿里云不同账号(跨账号)ECS服务器同地域如何实现免费内网互通? 2024-11-12
-
electron安装使用better-sqlite3并解决NODE_MODULE_VERSION xxx. This version of Node.js requires 2024-11-06
更多相关好文