php对象方法链式调用

2019-12-20  本文已影响0人  降水

对象方法链式操作


魔法函数 __call(function,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;
}
上一篇 下一篇

猜你喜欢

热点阅读