views:

27

answers:

2

Hello guys, In codeigniter we use a method call like this

$this->load->view();

I wanna know what's "load" exactly ? Is it a function or what ? And why it doesn't have two parentheses after it ? I wanna make something like this in my code so how can I do this ?

+2  A: 

load, a property on the object $this, is an instance of the CI_Loader class. It has a method called view().

CodeIgniter instantiates the Loader object in a fairly obtuse way, but you can visualize it like this:

class Loader {
  function view($view_name) {
    echo "View '$view_name' loaded!";
  }
}

class FooController{
  public $load;

  function __construct() {
    $this->load = new Loader();
  }
}

$foo = new FooController();
$foo->load->view("bar"); // => "View 'bar' loaded!"
/* ^    ^     ^
   |    |     |
   |    |     +--- view() is a method on the Loader object assigned to $foo's 'load' property
   |    |
   |    +--------- 'load' is a property on $foo, to which we've assigned an object of class Loader
   |
   +-------------- $foo is an instance of class FooController
*/
Jordan
Can we make an instance of a class in an another class definition ?
Lattice
Yes. Class definitions are global, so once PHP knows about a class we can create instances of it anywhere.
Jordan
A: 

You would do something like this:

class Controller {
    public $load = new Loader();
    //...
}

Then, you can access properties and methods on $load like this:

$controller = new Controller();
$controller->load->foo();

In CI, $load is just a property of the CI_Controller class, and an instance of the CI_Loader class.

Austin Hyde