PHP三種方式實現(xiàn)鏈式操作詳解
在php中有很多字符串函數(shù),例如要先過濾字符串收尾的空格,再求出其長度,一般的寫法是:
strlen(trim($str))
如果要實現(xiàn)類似js中的鏈式操作,比如像下面這樣應該怎么寫?
$str->trim()->strlen()
下面分別用三種方式來實現(xiàn):
方法一、使用魔法函數(shù)__call結(jié)合call_user_func來實現(xiàn)
思想:首先定義一個字符串類StringHelper,構(gòu)造函數(shù)直接賦值value,然后鏈式調(diào)用trim()和strlen()函數(shù),通過在調(diào)用的魔法函數(shù)__call()中使用call_user_func來處理調(diào)用關系,實現(xiàn)如下:
<?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();
終端執(zhí)行腳本:
php test.php
8
方法二、使用魔法函數(shù)__call結(jié)合call_user_func_array來實現(xiàn)
<?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() 函數(shù)用于向數(shù)組插入新元素。新數(shù)組的值將被插入到數(shù)組的開頭。
call_user_func()和call_user_func_array都是動態(tài)調(diào)用函數(shù)的方法,區(qū)別在于參數(shù)的傳遞方式不同。
方法三、不使用魔法函數(shù)__call來實現(xiàn)
只需要修改_call()為trim()函數(shù)即可:
public function trim($t)
{
$this->value = trim($this->value, $t);
return $this;
}
重點在于,返回$this指針,方便調(diào)用后者函數(shù)。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
PHP中可以自動分割查詢字符的Parse_str函數(shù)使用示例
這篇文章主要介紹了PHP中可以自動分割查詢字符的Parse_str函數(shù)使用示例,小編也沒見過的一個函數(shù),這下分割URL中的查詢字符串就方便了,需要的朋友可以參考下2014-07-07
ThinkPHP框架實現(xiàn)用戶信息查詢更新及刪除功能示例
這篇文章主要介紹了ThinkPHP框架實現(xiàn)用戶信息查詢更新及刪除功能,結(jié)合實例形式分析了thinkPHP框架數(shù)據(jù)庫配置、控制與模板調(diào)用實現(xiàn)信息查詢、更新、刪除等功能相關操作技巧,需要的朋友可以參考下2018-03-03
ThinkPHP中Common/common.php文件常用函數(shù)功能分析
這篇文章主要介紹了ThinkPHP中Common/common.php文件常用函數(shù)功能,通過注釋的形式詳細分析了C方法、tag方法、B方法及autoload方法的功能與代碼原理,需要的朋友可以參考下2016-05-05

