PHP链式调用怎么实现?-PHP问题

资源魔 36 0

PHP链式挪用的完成办法:一、应用邪术函数【_call】连系【call_user_func】来完成;二、应用邪术函数【_call】连系【call_user_func_array】来完成;三、没有应用邪术函数【_call】来完成。

PHP链式挪用的完成办法:

办法1、应用邪术函数__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

办法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();

阐明:

array_unshift(array,value1,value2,value3...)

array_unshift() 函数用于向数组拔出新元素。新数组的值将被拔出到数组的扫尾。

call_user_func()以及call_user_func_array都是静态挪用函数的办法,区分正在于参数的通报形式没有同。

办法3、没有应用邪术函数__call来完成

只要要修正_call()trim()函数便可:

public function trim($t)
{
  $this->value = trim($this->value, $t);
  return $this;
}

重点正在于,前往$this指针,不便挪用后者函数。

相干学习保举:PHP编程从入门到通晓

以上就是PHP链式挪用怎样完成?的具体内容,更多请存眷资源魔其它相干文章!

标签: php php教程 php故障解决 php使用问题 链式调用

抱歉,评论功能暂时关闭!