本篇文章給大家分享的是有關PHP實現鏈式調用的方法,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
PHP鏈式調用的實現方法:1、使用魔法函數【_call】結合【call_user_func】來實現;2、使用魔法函數【_call】結合【call_user_func_array】來實現;3、不使用魔法函數【_call】來實現。
方法一、使用魔法函數__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('0')->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('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實現鏈式調用的方法,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。