PHP三种方式实现链式操纵
发布时间:09/01 来源:未知 浏览:
关键词:
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('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视频教程》
以上就是PHP三种方式实现链式操纵的具体内容,更多请关注百分百源码网其它相关文章!