gpt4 book ai didi

PHP 分配另一个类的 $this

转载 作者:行者123 更新时间:2023-12-03 20:26:13 24 4
gpt4 key购买 nike

我一直想知道是否可以将另一个对象分配给 $this?

在 CodeIgniter 中,我从主 Controller 调用另一个 Controller 。

应用程序/ Controller /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_模块:

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

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

我怎样才能做到这一点?

感谢您的建议。

编辑:我尝试从 CI_Controller 扩展 MY_Module。但由于它已经实例化一次,因此会导致问题。

最佳答案

您无法“注入(inject)”对当前 $this 对象的引用。即使这是可能的,我也会强烈建议反对。

只需将引用分配给另一个变量并从中使用即可。

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

}

关于PHP 分配另一个类的 $this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6266736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com