2011-06-07 52 views
2

我一直想知道是否有可能分配另一個對象$ this?

在CodeIgniter中,我從主控制器調用另一個控制器。

應用/控制器/ 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)); 
    } 
} 

在稱爲類:

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

我想用實例化類的declaretion到My_Module類。這樣它就不會初始化相同的庫,也不會花費更多的資源。

我該如何做到這一點?

感謝您的建議。

編輯:我試圖從CI_Controller擴展MY_Module。但是由於它已經實例化了一次,這就造成了問題。

+0

不知道,是開始,因此只是一個:_Never_想這樣的事情了。 ;) – KingCrunch 2011-06-07 14:32:32

+0

請告訴我你不在PHP 4.x上工作......否則,在$ this =&CI_Controller :: get_instance();中,&符號是無用的,因爲在PHP 5.x中,所有的對象總是被傳遞參考(他們應該) – mkilmanas 2011-06-07 14:37:28

+0

編號我使用PHP 5.3 – Valour 2011-06-07 14:51:14

回答

5

你不能 「注入」 到當前的$this對象的引用。即使這是可能的,我會強烈建議反對。

只需將引用分配給另一個var並從中使用。

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

} 
+0

,但這不會讓我使用'$ this->'類似的語句。我總是必須像'$ this-> CI->'一樣使用。它會導致我的視​​圖文件出現問題。 – Valour 2011-06-07 14:53:23

1

這在PHP中是不可能的(因爲它應該)。

你應該改一下你的問題到更多的東西是這樣的:

我有兩個階級,他們兩人的初始化相同的庫(因此使用更多的資源)。 我該如何避免這種情況?

[例如這裏]