【问题标题】:PHP assign $this of another classPHP分配另一个类的$this
【发布时间】:2011-06-07 14:27:12
【问题描述】:

我一直想知道是否可以将另一个对象分配给 $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.
    }
}

我想对 My_Module 类使用实例化类的声明。这样它就不会初始化相同的库,也不会花费更多的资源。

我怎样才能做到这一点?

感谢您的建议。

编辑:我试图从 CI_Controller 扩展 MY_Module。但是由于它已经实例化了一次,所以它会导致问题。

【问题讨论】:

  • 不知道,要开始,因此只是:永远不要再考虑这样的事情。 ;)
  • 请告诉我你没有在 PHP 4.x 上工作...否则,$this =& CI_Controller::get_instance(); 和号是无用的,因为在 PHP 5.x 中所有对象总是通过引用传递(因为它们应该)

标签: php class codeigniter controller this-pointer


【解决方案1】:

您不能“注入”对当前$this 对象的引用。即使这是可能的,我也会强烈反对。

只需将引用分配给另一个 var 并从中使用。

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

}

【讨论】:

  • 但这不会让我使用 $this-> 之类的语句。我总是不得不使用$this->CI->。它会导致我的视​​图文件出现问题。
【解决方案2】:

这在 PHP 中是不可能的(应该如此)。

你应该把你的问题改写成这样:

我有两个类,它们都初始化相同的库(因此会占用更多资源)。 我怎样才能避免这种情况?

[此处示例]

【讨论】:

    猜你喜欢
    • 2011-06-13
    • 2017-10-20
    • 2015-08-30
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    相关资源
    最近更新 更多