Php 鏈式執行,PHP實現鏈式操作的三種方法詳解

2021-10-25 21:22:18 字數 1605 閱讀 1315

在php中有很多字串函式,例如要先過濾字串收尾的空格,再求出其長度,一般的寫法是:

strlen(trim($str))

如果要實現類似js中的鏈式操作,比如像下面這樣應該怎麼寫?

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

下面分別用三種方式來實現:

方法一、使用魔法函式__call結合call_user_func來實現

思想:首先定義乙個字串類stringhelper,建構函式直接賦值value,然後鏈式呼叫trim()和strlen()函式,通過在呼叫的魔法函式__call()中使用call_user_func來處理呼叫關係,實現如下:

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來實現

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實現鏈式操作的原理詳解

在乙個類中有多個方法,當你例項化這個類,並呼叫方法時只能乙個乙個呼叫,類似 db.php class db public function where code here public function order code here public function limit code here ...

php實現鏈式佇列

header content type text html charset utf 8 鏈式佇列 class node class queue public function init size 入隊操作 public function inq nickname else 出隊操作 public f...

php 鏈式語法

思路 鏈式語法就是物件呼叫方法執行賦值操作後返回乙個物件,那就可以接著呼叫方法,最後乙個方法返回具體sql語句 class sql public function where where 1 1 public function order order id desc public function ...