脚本宝典收集整理的这篇文章主要介绍了全局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
谢谢.
您在上面调用的方法是函数,而不是绑定到任何类的方法. 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,$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函数通过类链接全部内容,希望文章能够帮你解决全局PHP函数通过类链接所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。