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

yipeiwu_com6年前PHP代码库

本文实例讲述了PHP实现链式操作的三种方法。分享给大家供大家参考,具体如下:

在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相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

php集成环境xampp中apache无法启动问题解决方案

php集成环境xampp中apache无法启动问题解决方案

排查原因,发现是80端口被其它程序占用(很常见的事情╮(╯_╰)╭)。 解决方法 用记事本打开目录x:\xampp\apache\conf下的http.conf文件,将Listen:8...

php class中public,private,protected的区别以及实例分析

一,public,private,protected的区别public:权限是最大的,可以内部调用,实例调用等。protected: 受保护类型,用于本类和继承类调用。private:...

PHP的变量类型和作用域详解

PHP中变量的作用域可以分为:超全局(全局变量的特殊类型,在局部范围里可直接使用),全局,局部,静态(是局部变量的特殊类型)在PHP中,全局变量实际上是静态全局变量,如果不用unset显...

分享一则PHP定义函数代码

先贴代码 复制代码 代码如下: <?php     function table(){     &nb...

php动态函数调用方法

php中可以把函数名通过字符串的方式传递给一个变量,然后通过此变量动态调用函数 下面是一个简单的动态函数调用范例 <html> <head> <titl...