methods - Global PHP functions chaining through a Class -


is possible chain php functions through object/class?

i have on mind , imagine this:

$c = new chainer();  $c->strtolower('stackoverflow')->ucwords(/* value first function argument */)->str_replace('st', 'b', /* value first function argument */); 

this should produce:

backoverflow 

thanks.

do mean str_replace('st', 'b', ucwords(strtolower('stackoverflow'))) ?

the methods calling above functions, not methods tied class. chainer have implement these methods. if want (perhaps different purpose , example) implementation of chainer might this:

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;    } } 

this work in above example somewhat, call this:

$c = new chainer; echo $c->strtolower('stackoverflow')    ->ucwords()    ->str_replace('st', 'b') ; //backoverflow 

note never value of /* value first function argument */ out chain wouldn't make sense. maybe global variable, quite hideous.

the point is, can chain methods returning $this each time. next method called on returned value same object because returned (returned $this). important know methods start , stop chain.

i think implementation makes sense:

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 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(); } 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -