编程语言
首页 > 编程语言> > 全局PHP函数通过类链接

全局PHP函数通过类链接

作者:互联网

是否可以通过对象/类链接所有PHP函数?

我有这个想法,我想这样的事情:

$c = new Chainer();

$c->strtolower('StackOverFlow')->ucwords(/* the value from the first function argument */)->str_replace('St', 'B', /* the value from the first function argument */);

这应该产生:

Backoverflow

谢谢.

解决方法:

你的意思是做str_replace(‘St’,’B’,ucwords(strtolower(‘StackOverFlow’)))?

您在上面调用的方法是函数,而不是绑定到任何类的方法. Chainer必须实施这些方法.如果这是你想要做的(也许是为了一个不同的目的,这只是一个例子)你的Chainer实现可能如下所示:

class Chainer {
   private $string;
   public function strtolower($string) {
      $this->string = strtolower($string);
      return $this;
   }
   public function ucwords() {
      $this->string = ucwords($this->string);
      return $this;
   }
   public function str_replace($from, $to) {
      $this->string = str_replace($from, $to, $this->string);
      return $this;
   }
   public function __toString() {
      return $this->string;
   }
}

这在上面的例子中会有所作为,但你会这样称呼它:

$c = new Chainer;
echo $c->strtolower('StackOverFlow')
   ->ucwords()
   ->str_replace('St', 'B')
; //Backoverflow

请注意,您永远不会从第一个函数参数* /中获取/ *值的值,因为这没有意义.也许你可以用一个全局变量来做,但那将是非常可怕的.

关键是,你可以通过每次返回$this来链接方法.下一个方法是在返回的值上调用的,因为你返回了它是同一个对象(返回$this).重要的是要知道哪些方法启动和停止链.

我认为这种实现最有意义:

class Chainer {
   private $string;
   public function __construct($string = '') {
      $this->string = $string;
      if (!strlen($string)) {
         throw new Chainer_empty_string_exception;
      }
   }
   public function strtolower() {
      $this->string = strtolower($this->string);
      return $this;
   }
   public function ucwords() {
      $this->string = ucwords($this->string);
      return $this;
   }
   public function str_replace($from, $to) {
      $this->string = str_replace($from, $to, $this->string);
      return $this;
   }
   public function __toString() {
      return $this->string;
   }
}
class Chainer_empty_string_exception extends Exception {
   public function __construct() {
      parent::__construct("Cannot create chainer with an empty string");
   }
}

try {
   $c = new Chainer;
   echo $c->strtolower('StackOverFlow')
      ->ucwords()
      ->str_replace('St', 'B')
   ; //Backoverflow
}
catch (Chainer_empty_string_exception $cese) {
   echo $cese->getMessage();
}

标签:php,methods,chaining
来源: https://codeday.me/bug/20190715/1471366.html