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

所属分类: 网络编程 / PHP编程 阅读数: 1929
收藏 0 赞 0 分享

在php中有很多字符串函数,例如要先过滤字符串收尾的空格,再求出其长度,一般的写法是:

strlen(trim($str))

如果要实现类似js中的链式操作,比如像下面这样应该怎么写?

$str->trim()->strlen()

下面分别用三种方式来实现:

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

思想:首先定义一个字符串类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

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

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

说明:

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实现像JSP,ASP里Application那样的全局变量

用php实现像JSP,ASP里Application那样的全局变量
收藏 0 赞 0 分享

自动分页的不完整解决方案

自动分页的不完整解决方案
收藏 0 赞 0 分享

FCKeditor的安装(PHP)

FCKeditor的安装(PHP)
收藏 0 赞 0 分享

mysql5详细安装教程

mysql5详细安装教程
收藏 0 赞 0 分享

isset和empty的区别

isset和empty的区别
收藏 0 赞 0 分享

php5.2时间相差8小时

php5.2时间相差8小时
收藏 0 赞 0 分享

安装APACHE

安装APACHE
收藏 0 赞 0 分享

PHP5 安装方法

PHP5 安装方法
收藏 0 赞 0 分享

PHP has encountered an Access Violation

PHP has encountered an Access Violation
收藏 0 赞 0 分享

MYSQL环境变量设置方法

本文介绍了mysql数据库中环境变量的设置方法,如何设置mysql数据库的环境变量,有需要的朋友参考下
收藏 0 赞 0 分享
查看更多