Вы хотите сделать 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();
}