首頁  >  文章  >  後端開發  >  php鍊式操作的實作方法有哪些

php鍊式操作的實作方法有哪些

青灯夜游
青灯夜游原創
2021-05-28 17:36:222323瀏覽

php實作鍊式運算的方法:1、使用魔法函式「__call」結合「call_user_func」來實作;2、使用魔法函式「__call」結合「call_user_func_array」來實現;3、利用trim()函數來實現。

php鍊式操作的實作方法有哪些

本教學操作環境:windows7系統、PHP7.1版,DELL G3電腦

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

strlen(trim($str))

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

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

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

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

想法:先定義一個字串類別StringHelper,建構子直接賦值value,然後鍊式呼叫trim()和strlen()函數,透過在呼叫的魔法函數__call()中使用call_user_func來處理呼叫關係,實作如下:

<?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(&#39;0&#39;)->strlen();

終端執行腳本:

php test.php 
8

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

<?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(&#39;0&#39;)->strlen();

說明:

array_unshift(array,value1,value2,value3...)

array_unshift() 函數用於向陣列插入新元素。新數組的值將插入到數組的開頭。

call_user_func()call_user_func_array都是動態呼叫函數的方法,差別在於參數的傳遞方式不同。

方法三、不使用魔法函數__call,利用trim()函數來實作

只需要修改_call()trim()函數即可:

public function trim($t)
{
  $this->value = trim($this->value, $t);
  return $this;
}

重點在於,傳回$this指針,方便呼叫後者函數。

推薦學習:《PHP影片教學

以上是php鍊式操作的實作方法有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn