源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

PHP实现链式操作的三种方法详解

  • 时间:2020-03-09 13:59 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:PHP实现链式操作的三种方法详解
本文实例讲述了PHP实现链式操作的三种方法。分享给大家供大家参考,具体如下: 在php中有很多字符串函数,例如要先过滤字符串收尾的空格,再求出其长度,一般的写法是:
strlen(trim($str))

如果要实现类似js中的链式操作,比如像下面这样应该怎么写?
$str->trim()->strlen()

下面分别用三种方式来实现: [b]方法一、使用魔法函数__call结合call_user_func来实现[/b] [b]思想:[/b]首先定义一个字符串类StringHelper,构造函数直接赋值value,然后链式调用trim()和strlen()函数,通过在调用的魔法函数__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();

终端执行脚本:
php test.php 
8

[b]方法二、使用魔法函数__call结合call_user_func_array来实现[/b]
<?php
class 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();

[b]说明:[/b] array_unshift(array,value1,value2,value3...) [code]array_unshift()[/code] 函数用于向数组插入新元素。新数组的值将被插入到数组的开头。 [code]call_user_func()[/code]和[code]call_user_func_array[/code]都是动态调用函数的方法,区别在于参数的传递方式不同。 [b]方法三、不使用魔法函数__call来实现[/b] 只需要修改[code]_call()[/code]为[code]trim()[/code]函数即可:
public function trim($t)
{
  $this->value = trim($this->value, $t);
  return $this;
}

重点在于,返回$this指针,方便调用后者函数。 更多关于PHP相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/43.htm]php面向对象程序设计入门教程[/url]》、《[url=http://www.1sucai.cn/Special/623.htm]PHP数组(Array)操作技巧大全[/url]》、《[url=http://www.1sucai.cn/Special/348.htm]PHP基本语法入门教程[/url]》、《[url=http://www.1sucai.cn/Special/357.htm]PHP运算与运算符用法总结[/url]》、《[url=http://www.1sucai.cn/Special/47.htm]php字符串(string)用法总结[/url]》、《[url=http://www.1sucai.cn/Special/84.htm]php+mysql数据库操作入门教程[/url]》及《[url=http://www.1sucai.cn/Special/231.htm]php常见数据库操作技巧汇总[/url]》 希望本文所述对大家PHP程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部