PHP實現鏈式操作的三種方法詳解

2022-08-29 13:33:21 字數 1519 閱讀 9101

這篇文章主要介紹了php實現鏈式操作的三種方法,結合例項形式分析了php鏈式操作的相關實現技巧與使用注意事項,需要的朋友可以參考下

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

strlen(trim($str))

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

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

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

方法

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

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

<?php

class

stringhelper

function __call($function, $args)

function

strlen

() }

$str = new stringhelper(" sd f 0");

echo

$str->trim('0')->strlen();

終端執行指令碼:

php test.php 

8

方法

二、使用魔法函式__call結合call_user_func_array來實現

<?php

class

stringhelper

function __call($function, $args)

function

strlen

() }

$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指標,方便呼叫後者函式。

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

在php中有很多字串函式,例如要先過濾字串收尾的空格,再求出其長度,一般的寫法是 strlen trim str 如果要實現類似js中的鏈式操作,比如像下面這樣應該怎麼寫?str trim strlen 下面分別用三種方式來實現 方法一 使用魔法函式 call結合call user func來實現 ...

Php 鏈式執行,PHP實現鏈式操作的原理詳解

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

PHP爬蟲的三種方法

定義 file get contents 函式把整個檔案讀入乙個字串中。語法 file get contents path,include path,context,start,max length 引數 描述path 必需。規定要讀取的檔案。include path 可選。如果也想在 includ...