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

來源:互聯網
上載者:User
這篇文章主要介紹了PHP實現鏈式操作的三種方法,結合執行個體形式分析了php鏈式操作的相關實現技巧與使用注意事項,需要的朋友可以參考下

具體如下:

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


strlen(trim($str))


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


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


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

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

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


<?phpclass 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 8


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


<?phpclass 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中字串的三種表示方式

php中常用字串函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.