对象方法链式操作
魔法函数 __call(
args)
对象调用不存在的方法的时候,会自动调用
调用函数的方法
call_user_func($function, $arg1, $arg2)
调用函数的方法
call_user_func_array($function, [$arg1, $arg2])
调用函数的方法
call_user_func_array([$foo, "bar"], ["three", "four"])
$foo->bar() method with 2 arguments
array_unshift()
函数用于向数组插入新元素。新数组的值将被插入到数组的开头。
1 使用魔法函数__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();
2 使用魔法函数__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();
3 不使用魔法函数__call
来实现, 重点在于返回$this
指针,方便调用后者函数。
public function trim($t)
{
$this->value = trim($this->value, $t);
return $this;
}
网友评论