您的位置 首页 技术

PHP链式调用怎么实现?

PHP链式调用的实现方法:1、使用魔法函数【_call】结合【call_user_func】来实现;2、使用魔法函数【_call】结合【call_user_func_array】来…

PHP链式调用的实现方法:1、使用魔法函数【_call】结合【call_user_func】来实现;2、使用魔法函数【_call】结合【call_user_func_array】来实现;3、不使用魔法函数【_call】来实现。

PHP链式调用的实现方法:

方法一、使用魔法函数__call结合call_user_func来实现

思想:首先定义一个字符串类StringHelper,构造函数直接赋值value,然后链式调用trim()strlen()函数,通过在调用的魔法函数__call()中使用call_user_func来处理调用关系,实现如下:

<?phpclass 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();

终端执行脚本:

php test.php 8

方法二、使用魔法函数__call结合call_user_func_array来实现

<?phpclass StringHelper {  private $value;  function __construct($value)  {    $this->value = $value;  }  function __call($function, $args){    array_unshift($args, $this->value);    $this->value = call_user_func_array($function, $args);    return $this;  }  function strlen() {    return strlen($this->value);  }}$str = new StringHelper(" sd f 0");echo $str->trim('0')->strlen();

说明:

array_unshift(array,value1,value2,value3...)

array_unshift() 函数用于向数组插入新元素。新数组的值将被插入到数组的开头。

call_user_func()call_user_func_array都是动态调用函数的方法,区别在于参数的传递方式不同。

方法三、不使用魔法函数__call来实现

只需要修改_call()trim()函数即可:

public function trim($t){  $this->value = trim($this->value, $t);  return $this;}

重点在于,返回$this指针,方便调用后者函数。

相关学习推荐:PHP编程从入门到精通

以上就是PHP链式调用怎么实现?的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/89464.html

为您推荐

返回顶部