2

I have been wondering is it possible to assign another object to $this?

In CodeIgniter I am calling another controller from main controller.

application/controllers/module.php

Class Module extends CI_Controller {
    public function __construct() {
        parent::__construct();
    }

    public function _remap($class, $args = array()) {
        // doing some checks that is there a valid file, class and method
        // assigning the $method.
        // including MY_Module class. I'am extending every module from this class.
        // then:
        $EG = new $class();
        call_user_func_array(array(&$EG, $method), array_slice($this->uri->rsegments, 3));
    }
}

In called class:

Class Users extends MY_Module
{
    public function __construct() {
        parent::__construct();
    }

    public function index() {
        // Want to use this class and method like it is a codeigniter controller.
    }
}

MY_Module:

Class My_Module {
    public function __construct() {
        $this =& CI_Controller::get_instance(); // Here is problem.
    }
}

I want to use instantiated class' declaretion to My_Module class. So that it wont initialize same libraries and won't spend more resource.

How can I accomplish that?

Thanks for advices.

EDIT: I tried to extend MY_Module from CI_Controller. But since its already instantiated once, it is causing problems.

Valour
  • 773
  • 10
  • 32
  • Don't know, were to start, thus just a: _Never_ think about something like this anymore. ;) – KingCrunch Jun 07 '11 at 14:32
  • Please tell me you're not working on PHP 4.x... Otherwise, in `$this =& CI_Controller::get_instance();` ampersand is useless because in PHP 5.x all objects are always passed by reference (as they should) – mkilmanas Jun 07 '11 at 14:37

2 Answers2

5

You can't "inject" a reference to your current $this object. And even if that was possibile i would strongly advise against.

Just assign the reference to another var and use from it.

public function __construct() {
    $yourSingleton = CI_Controller::get_instance(); 

}
dynamic
  • 46,985
  • 55
  • 154
  • 231
  • but this wont let me to use `$this->` like statements. I always have to use like `$this->CI->`. and it will cause problems with my view files. – Valour Jun 07 '11 at 14:53
1

This is not possible in PHP (as it should).

You should rephrase your question into something more like this:

I have two classes and both of them initialize the same libraries (thus using up more resources). How can I avoid this?

[example here]

Evert
  • 93,428
  • 18
  • 118
  • 189