用php做出三种链式操作的方法分别是使用魔法函数call结合call_user_func来实现,使用魔法函数call结合call_user_func_array来实现以及不使用魔法函数call来实现。
在php中有很多字符串函数,例如要先过滤字符串收尾的空格,再求出其长度,一般的写法是:
strlen(trim($str))
如果要实现类似js中的链式操作,比如像下面这样应该怎么写?
$str->trim()->strlen()
下面分别用三种方式来实现:
方法一、使用魔法函数call结合call_user_func来实现
立即学习“PHP免费学习笔记(深入)”;
思想:首先定义一个字符串类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
方法二、使用魔法函数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指针,方便调用后者函数。
方法三、不使用魔法函数call来实现
只需要修改_call()为trim()函数即可:
public function trim($t)
{
$this->value = trim($this->value, $t);
return $this;
}重点在于,返回$this指针,方便调用后者函数。
相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
相关阅读:
以上就是PHP的链式操作有几种实现方式的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号