美文网首页
php对象方法链式调用

php对象方法链式调用

作者: 降水 | 来源:发表于2019-12-20 17:15 被阅读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;
}

相关文章

  • php对象方法链式调用

    对象方法链式操作 魔法函数 __call(args)对象调用不存在的方法的时候,会自动调用 调用函数的方法 cal...

  • Java链式编程

    概念 所谓链式,也就是每次调用对象方法后返回的都是该对象本身,而该对象又可以继续调用方法。 例子

  • jquery高级

    1.jquery可以链式编程 原理:是对象中的方法返回该对象,然后可以继续调用 在jquery中有些方法是破坏链式...

  • jQuery 链式调用,触发事件

    jquery链式调用: jquery对象的方法会在执行完后返回这个jquery对象,所有jquery对象的方法可以...

  • jquery链式调用及动画、触发事件

    jquery链式调用: jquery对象的方法会在执行完后返回这个jquery对象,所有jquery对象的方法可以...

  • 链式调用及动画、触发事件

    jquery链式调用: jquery对象的方法会在执行完后返回这个jquery对象,所有jquery对象的方法可以...

  • 15_day jQuery 链式调用及动画、触发事件

    jquery链式调用: jquery对象的方法会在执行完后返回这个jquery对象,所有jquery对象的方法可以...

  • js链式调用 动画

    jquery链式调用: jquery对象的方法会在执行完后返回这个jquery对象,所有jquery对象的方法可以...

  • js链式调用 动画

    jquery链式调用: jquery对象的方法会在执行完后返回这个jquery对象,所有jquery对象的方法可以...

  • jQuery的动画 和 jQuery的事件

    1. jquery链式调用 jquery对象的方法会在执行完后返回这个jquery对象,所有jquery对象的方法...

网友评论

      本文标题:php对象方法链式调用

      本文链接:https://www.haomeiwen.com/subject/ocaqyctx.html