PHP 三種方式實現鏈式操做

在php中有不少字符串函數,例如要先過濾字符串收尾的空格,再求出其長度,通常的寫法是:php

strlen(trim($str))

若是要實現相似js中的鏈式操做,好比像下面這樣應該怎麼寫?shell

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

終端執行腳本:this

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() 函數用於向數組插入新元素。新數組的值將被插入到數組的開頭。code

call_user_func()call_user_func_array都是動態調用函數的方法,區別在於參數的傳遞方式不一樣。字符串

方法3、不使用魔法函數__call來實現

只須要修改_call()trim()函數便可:io

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

重點在於,返回$this指針,方便調用後者函數。function

相關文章
相關標籤/搜索