您的意思是做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
注意,你永遠不會從鏈得到/* the value from the first function argument */
值退了出來,因爲這是沒有意義的。也許你可以用全局變量來做到這一點,但那會很糟糕。
重點是,您可以通過每次返回$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函數」是什麼意思?所有內置的PHP函數,例如字符串,數組,mysql函數?我認爲這是不可能的,因爲每個函數都應該返回一個對象。 –
通過'$ c-> strtolower(ucwords(str_replace('St','B','StackOverFlow'))''做這個優點會是什麼?可讀性? – Lawyerson