《PHP學習:PHP三種方式實現鏈式操作詳解》要點:
本文介紹了PHP學習:PHP三種方式實現鏈式操作詳解,希望對您有用。如果有疑問,可以聯系我們。
PHP教程在php中有很多字符串函數,例如要先過濾字符串收尾的空格,再求出其長度,一般的寫法是:
PHP教程
strlen(trim($str))
PHP教程如果要實現類似js中的鏈式操作,比如像下面這樣應該怎么寫?
PHP教程
$str->trim()->strlen()
PHP教程下面分別用三種方式來實現:
PHP教程方法一、使用魔法函數__call結合call_user_func來實現
PHP教程思想:首先定義一個字符串類StringHelper,構造函數直接賦值value,然后鏈式調用trim()和strlen()函數,通過在調用的魔法函數__call()中使用call_user_func來處理調用關系,實現如下:
PHP教程
<?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教程終端執行腳本:
PHP教程php test.php
PHP教程8
PHP教程方法二、使用魔法函數__call結合call_user_func_array來實現
PHP教程
<?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();
PHP教程說明:
PHP教程
array_unshift(array,value1,value2,value3...)
PHP教程array_unshift() 函數用于向數組插入新元素.新數組的值將被插入到數組的開頭.
PHP教程call_user_func()和call_user_func_array都是動態調用函數的方法,區別在于參數的傳遞方式不同.
PHP教程方法三、不使用魔法函數__call來實現
PHP教程只需要修改_call()為trim()函數即可:
PHP教程
public function trim($t)
{
$this->value = trim($this->value, $t);
return $this;
}
PHP教程重點在于,返回$this指針,方便調用后者函數.
PHP教程以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持維易PHP.