views:

31

answers:

1

Hello Geeks
I have seen many php scripts in which you can cascade class method to produce a specific functionality for example as in codeigniter when you load a view you would type

<?php
class Posts extends Controller
    {
        function index() {
            $this->load->view("BlaBla");
        }
    }
?>

I am not completely sure if these are cascaded methods or what butI don't have enough experience to hack the codeigniter core and figure out myself.
Can anyone tell me how to do this or guide me to some tutorial or so

A: 

Every method must return its class instance, like:

class A{
  function B(){
    //do stuff
    return $this;
  }
  function C(){
    //do stuff
    return $this;
  }
  function D(){
    return $this->B()->C()->B()->B()->C();
  }
}

or you can build your own cahining class to chain anything:

class Ch{  
  static private $i; 
    public static function i($arg){
    if  (!self::$i instanceof self){
      self::$i = new self();
    }
    self::$i->data=$arg;
        return self::$i;
    }  
  function __call($name,$args){
    array_unshift($args,$this->data);
    $this->data=call_user_func_array($name,$args);
    return $this;
  }
  function get(){
    return $this->data;
  }
}


echo Ch::i('Hello world')->trim('Hld')->str_repeat(5)->substr(5,7)->strtoupper()->get();
codez