全局PHP函数通过类链接
发布时间:2020-12-13 22:02:14 所属栏目: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 argum
是否可以通过对象/类链接所有
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,$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(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |