php函数连续调用/链式调用方法详解与案例分析

Song1108 次浏览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();

提交评论

请登录后评论

用户评论

    当前暂无评价,快来发表您的观点吧...

更多相关好文

    当前暂无更多相关好文推荐...