温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP实现链式操作的方法有哪些

发布时间:2020-10-15 17:27:48 来源:亿速云 阅读:140 作者:小新 栏目:编程语言

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实现链式操作的方法有哪些大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI