met*_*rce 3 php methods chaining
是否可以通过对象/类链接所有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 */);
Run Code Online (Sandbox Code Playgroud)
这应该产生:
Backoverflow
Run Code Online (Sandbox Code Playgroud)
谢谢.
看一下:
http://php.net/manual/en/language.oop5.magic.php
特别:
http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
并且可以:
http://php.net/manual/en/function.call-user-func-array.php
正如许多人发布他们的例子,我也会尝试:
<?php
class Chainer
{
protected $buffer = null;
public function __call($name, $args) {
if (method_exists($this, $name)) {
$this->buffer = call_user_func_array(array($this, $name), $args);
}
elseif (function_exists($name)) {
if ($this->buffer !== null) {
$args[] = $this->buffer;
}
$this->buffer = call_user_func_array($name, $args);
}
return $this;
}
public function strpos($needle, $offset = 0) {
return strpos($this->buffer, $needle, $offset);
}
public function __toString() {
return (string)$this->buffer;
}
}
$c = new Chainer();
echo $c->strtolower('StackOverFlow')->ucwords()->str_replace('St', 'B')->strpos('overflow'); // output: 4
Run Code Online (Sandbox Code Playgroud)