本文實(shí)例講述了PHP實(shí)現(xiàn)鏈?zhǔn)讲僮鞯娜N方法。分享給大家供大家參考,具體如下:
在php中有很多字符串函數(shù),例如要先過(guò)濾字符串收尾的空格,再求出其長(zhǎng)度,一般的寫(xiě)法是:
如果要實(shí)現(xiàn)類似js中的鏈?zhǔn)讲僮鳎热缦裣旅孢@樣應(yīng)該怎么寫(xiě)?
下面分別用三種方式來(lái)實(shí)現(xiàn):
方法一、使用魔法函數(shù)__call結(jié)合call_user_func來(lái)實(shí)現(xiàn)
思想:首先定義一個(gè)字符串類StringHelper,構(gòu)造函數(shù)直接賦值value,然后鏈?zhǔn)秸{(diào)用trim()和strlen()函數(shù),通過(guò)在調(diào)用的魔法函數(shù)__call()中使用call_user_func來(lái)處理調(diào)用關(guān)系,實(shí)現(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í)行腳本:
方法二、使用魔法函數(shù)__call結(jié)合call_user_func_array來(lái)實(shí)現(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();
說(shuō)明:
array_unshift(array,value1,value2,value3...)
array_unshift()
函數(shù)用于向數(shù)組插入新元素。新數(shù)組的值將被插入到數(shù)組的開(kāi)頭。
call_user_func()
和call_user_func_array
都是動(dòng)態(tài)調(diào)用函數(shù)的方法,區(qū)別在于參數(shù)的傳遞方式不同。
方法三、不使用魔法函數(shù)__call來(lái)實(shí)現(xiàn)
只需要修改_call()
為trim()
函數(shù)即可:
public function trim($t)
{
$this->value = trim($this->value, $t);
return $this;
}
重點(diǎn)在于,返回$this指針,方便調(diào)用后者函數(shù)。
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語(yǔ)法入門(mén)教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- PHP實(shí)現(xiàn)的連貫操作、鏈?zhǔn)讲僮鲗?shí)例
- PHP簡(jiǎn)單數(shù)據(jù)庫(kù)操作類實(shí)例【支持增刪改查及鏈?zhǔn)讲僮鳌?/li>
- PHP三種方式實(shí)現(xiàn)鏈?zhǔn)讲僮髟斀?/li>
- PHP對(duì)象鏈?zhǔn)讲僮鲗?shí)現(xiàn)原理分析
- PHP實(shí)現(xiàn)鏈?zhǔn)讲僮鞯暮诵乃枷?/li>
- PHP實(shí)現(xiàn)鏈?zhǔn)讲僮鞯脑碓斀?/li>
- php類自動(dòng)裝載、鏈?zhǔn)讲僮鳌⒛g(shù)方法實(shí)現(xiàn)代碼
- PHP封裝類似thinkphp連貫操作數(shù)據(jù)庫(kù)Db類與簡(jiǎn)單應(yīng)用示例
- thinkPHP5框架數(shù)據(jù)庫(kù)連貫操作之cache()用法分析
- thinkphp連貫操作實(shí)例分析
- php鏈?zhǔn)讲僮鞯膶?shí)現(xiàn)方式分析