PHP三种方式实现链式操作-php教程

资源魔 32 0
正在php中有不少字符串函数,例如要先过滤字符串收尾的空格,再求出其长度,普通的写法是:

strlen(trim($str))

假如要完成相似js中的链式操作,比方像上面这样应该怎样写?

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

上面辨别用三种形式来完成:

办法1、应用邪术函数__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

办法2、应用邪术函数__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都是静态挪用函数的办法,区分正在于参数的通报形式没有同。

办法3、没有应用邪术函数__call来完成

只要要修正_call()为trim()函数便可:

public function trim($t)
{
    $this->value = trim($this->value, $t);
    return $this;
}

重点正在于,前往$this指针,不便挪用后者函数。

保举:《PHP视频教程》

以上就是PHP三种形式完成链式操作的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学 链式

抱歉,评论功能暂时关闭!